Examples of how to subtract a number to each element of a matrix in python using numpy:
Table of contents
Using - operator
A solution is to use the - operator, example:
>>> import numpy as np>>> a = np.array(([1,2,3],[4,5,6],[7,8,9]))>>> aarray([[1, 2, 3],[4, 5, 6],[7, 8, 9]])>>> a = a - 1>>> aarray([[0, 1, 2],[3, 4, 5],[6, 7, 8]])
Avec la function numpy subtract()
Another solution is to use the numpy function subtract
>>> import numpy as np>>> x1 = np.arange(9.0).reshape((3, 3))>>> x1array([[ 0., 1., 2.],[ 3., 4., 5.],[ 6., 7., 8.]])>>> x2 = np.ones(9).reshape((3, 3))>>> x2array([[ 1., 1., 1.],[ 1., 1., 1.],[ 1., 1., 1.]])>>> np.subtract(x1, x2)array([[-1., 0., 1.],[ 2., 3., 4.],[ 5., 6., 7.]])
References
| Links | Site |
|---|---|
| numpy.subtract | scipy doc |
| Sum one number to every element in a list (or array) in Python | stackoverflow |
| numpy.add | numpy doc |
