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

Daidalos June 13, 2019


Examples of how to add 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([[ 2,  3,  4],
       [ 5,  6,  7],
       [ 8,  9, 10]])

Avec la function numpy add()

Another solution is to use the numpy function add

>>> 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.add(x1, x2)
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.],
       [ 7.,  8.,  9.]])

References

Links Site
Sum one number to every element in a list (or array) in Python stackoverflow
numpy.add numpy doc

Licence


Activity


Google Ads