Numpy matrix multiply by scalar

In this article, we have explained how to multiply each element of a Numpy matrix by a scalar value in Python.

Table of contents:

  1. Numpy matrix multiply by scalar
  2. Python Code Example
  3. Conclusion

Numpy matrix multiply by scalar

Numpy matrix multiply by scalar

In Numpy, if you want to multiply each element in an Numpy matrix or array by the same scalar value, then we can simply multiply the Numpy matrix and scalar. It will multiply each element in the Numpy with the scalar and return a new Numpy matrix with updated elements.

The code snippet to do this is as follows:

new_matrix = matrix * scalar

If you wish to modify the original Numpy matrix, assign the output of multiplication to the original Numpy matrix. The code snippet to do this as follows:

matrix = matrix * scalar

Python Code Example

The complete Python code example is as follows:

import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print ("Original matrix = ")
print (matrix)
scalar = 2
new_matrix = matrix * scalar
print ("Matrix x Scalar = ")
print (new_matrix)


Original matrix = 
[[1 2 3]
 [4 5 6]]

Matrix x Scalar = 
[[ 2  4  6]
 [ 8 10 12]]

As you see, all elements have been multiplied by the scalar 2.


This is a better approach than traversing all elements one by one and multiplying each by a scalar. The approach presented in much more efficient in Python.