Matrices multiplication is a very important concept to manage data because it is used very frequently in many data operations and manipulation. In this article, we will give you a very good idea about matrices multiplication.
Before jumping into the programming part first, you have to understand how matrices multiplication is done or what kind of rule-following. You can visit this link for the matrix multiplication rule.
There are many programs of square matrix multiplication on the internet but in this article, you will learn rectangular matrix multiplication as well. In one example we will do matrices multiplication with the help of the “NumPy” library which is fast and efficient.
Square Matrix
in square matrix multiplication no need to check the base of matrices directly you can use the row-column rule.
A=[[1,1], [2,2]] B=[[3,3], [4,4]] C = [[0]*len(B) for i in range(len(B))] # list initialization M=0 for i in range(len(A)): # len(A) = len(B) because of square matrix for j in range(len(A)): for k in range(len(A)): M += A[i][k]*B[k][j] C[i][j] = M M=0 print(C)
Output:
[[7, 7], [14, 14]]
Rectangular Matrix
In rectangular matrix multiplication, you have to check the base of the matrix. The columns of the first matric must be equal to the row of the second matrix.
A=[[2,2,2],[1,1,1]] B=[[1,1],[2,2],[3,3]] rowA = len(A) colA = len(A[0]) rowB = len(B) colB = len(B[0]) M=0 if colA == rowB: c = [[0]*rowA for i in range(colB)] for i in range(rowA): for j in range(colB): for k in range(colA): M += a[i][k]*b[k][j] C[i][j] = M M=0 else: print("Multiplication Not Possiable.") print(C)
Output:
[[12, 12], [6, 6]]
Matrix Multiplication (NUMPY)
import numpy as np C = np.dot(A,B) print(C)
Output:
[[12, 12], [6, 6]]