Two matrices are compatible for multiplication if the number of columns of 1 matrix is equal to the number of rows of the other matrix.
For example, if matrix 1 has dimensions a * N and matrix 2 has dimensions N * b, then the resulting matrix has dimensions of a * b.
The illustration below shows how this is done:
To multiply two matrices use the dot()
function of NumPy. It takes only 2 arguments and returns the product of two matrices.
The general syntax is :
np.dot(x,y)
where x and y are two matrices of size a * M and M * b, respectively.
The following code shows an example of multiplying matrices in NumPy:
import numpy as np# two dimensional arraysm1 = np.array([[1,4,7],[2,5,8]])m2 = np.array([[1,4],[2,5],[3,6]])m3 = np.dot(m1,m2)print(m3)# three dimensional arraysm1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])m2 = ([3, 4, 6],[5, 6, 7],[6,56, 7])m3 = np.dot(m1,m2)print(m3)