With matrices, unlike with numbers, the order of multiplication matters. Two matrices can be multiplied only if the first (left) matrix's number of columns is equal to the second (right) matrix's number of rows. So, for example, the matrix , which is 3 x 2, can only be multiplied with matrices that have two rows, but those matrices can have any number of columns. The final answer of the multiplication will have the same number of rows as the first (left) matrix and the same number of columns as the second (right) matrix. So if we multiply M, which is 3 by 2, by a matrix N, which is 2 by 21, the final answer M * N will be a matrix which is 3 by 21, that is, a matrix that has three rows and 21 columns. We can't multiple N * M, as N has 21 columns and M has two rows, and these two numbers would need to be equal.
Each entry of the result matrix is composed by taking the product of the corresponding row in the first matrix and corresponding column in the second matrix. To take this product, multiply the first item of the row together with the first item of the column, and add the the second item of the row together with the second item of the column, and keep summing until we run out of items to get the final answer.
So, for example, consider the matrix , which is 2 x 2. The final result of M * P will be 3 x 2, which written out entry by entry is the following:
Let's compute each entry:
- (M row 1)*(P column 1), would be (1 2) times (7 9) or 1*7+2*9=25
- (M row 1)*(P column 2), would be (1 2) times (8 10) or 1*8+2*10=28
- (M row 2)*(P column 1), would be (3 4) times (7 9) or 3*7+4*9=57
- (M row 2)*(P column 2), would be (3 4) times (8 10) or 3*8+4*10=64
- (M row 3)*(P column 1), would be (5 6) times (7 9) or 4*7+6*9=89
- (M row 2)*(P column 2), would be (5 6) times (8 10) or 5*8+6*10=100
So, our final matrix is this:
Matrices in Python, once specified using the numpy module, can be multiplied with the * symbol.
Thus, we have this:
import numpy as np
M=np.matrix('1 2; 3 4; 5 6')
P=np.matrix('7 8; 9 10')
print(M*P)
Which prints the following:
matrix([[ 25, 28],
[ 57, 64],
[ 89, 100]])