NumPy Matrix Multiplication
NumPy matrix multiplication can be done by the following three methods.
- multiply(): element-wise matrix multiplication.
- matmul(): matrix product of two arrays.
- dot(): dot product of two arrays.
1. NumPy Matrix Multiplication Element Wise
If you want element-wise matrix multiplication, you can use multiply() function.
import numpy as np
arr1 = np.array([[1, 2],
[3, 4]])
arr2 = np.array([[5, 6],
[7, 8]])
arr_result = np.multiply(arr1, arr2)
print(arr_result)
Output
[[ 5 12]
[21 32]]
2. Matrix Product of Two NumPy Arrays
If you want the matrix product of two arrays, use matmul() function.
import numpy as np
arr1 = np.array([[1, 2],
[3, 4]])
arr2 = np.array([[5, 6],
[7, 8]])
arr_result = np.matmul(arr1, arr2)
print(f'Matrix Product of arr1 and arr2 is:\n{arr_result}')
arr_result = np.matmul(arr2, arr1)
print(f'Matrix Product of arr2 and arr1 is:\n{arr_result}')
Output
Matrix Product of arr1 and arr2 is:
[[19 22]
[43 50]]
Matrix Product of arr2 and arr1 is:
[[23 34]
[31 46]]
3. Dot Product of Two NumPy Arrays
The numpy dot() function returns the dot product of two arrays. The result is the same as the matmul() function for one-dimensional and two-dimensional arrays.
import numpy as np
arr1 = np.array([[1, 2],
[3, 4]])
arr2 = np.array([[5, 6],
[7, 8]])
arr_result = np.dot(arr1, arr2)
print(f'Dot Product of arr1 and arr2 is:\n{arr_result}')
arr_result = np.dot(arr2, arr1)
print(f'Dot Product of arr2 and arr1 is:\n{arr_result}')
arr_result = np.dot([1, 2], [5, 6])
print(f'Dot Product of two 1-D arrays is:\n{arr_result}')
Output
Dot Product of arr1 and arr2 is:
[[19 22]
[43 50]]
Dot Product of arr2 and arr1 is:
[[23 34]
[31 46]]
Dot Product of two 1-D arrays is:
17