How to subtract a number to each element of a matrix in python ?

Daidalos June 13, 2019


Examples of how to subtract a number to each element of a matrix in python using numpy:

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]))
>>> a
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> a = a - 1
>>> a
array([[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))
>>> x1
array([[ 0.,  1.,  2.],
       [ 3.,  4.,  5.],
       [ 6.,  7.,  8.]])
>>> x2 = np.ones(9).reshape((3, 3))
>>> x2
array([[ 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

Licence


Activity


Google Ads