Python Program to Multiply Two Matrices
The product of two matrices A and B is denoted as AB, and can be computed if the number of columns in matrix A is equal to the number of rows in matrix B. In other words, if A is an m x n matrix and B is an n x p matrix, then their product AB is an m x p matrix.
To compute the product of two matrices, you need to multiply the corresponding elements in each row of the first matrix with the corresponding elements in each column of the second matrix, and then sum the products. This operation is carried out for each element in the resulting matrix.
For example, consider the following matrices:
A =
[
1 2 3
4 5 6
]
B =
[
7 8
9 10
11 12
]
A matrix is represented as m x n. m is number of rows and m is number of rows. The A is respresented as 3 x 2 matrix, and B is represented as 2 x 3.
For multiplication, AB then n of A matrix should be equal to m of B matrix, and the resultant matrix will be 2 of A x 2 of B.
The product of matrices A and B is AB, which can be calculated as follows:
AB = [ (1x7 + 2x9 + 3x11) (1x8 + 2x10 + 3x12)
(4x7 + 5x9 + 6x11) (4x8 + 5x10 + 6x12) ]
= [
58 64
139 154 ]
Thus, the product of matrices A and B is a 2 x 2 matrix with elements 58, 64, 139, and 154.
Python Code :
The below Python program to multiply two matrices:
# Define matrices A and B
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
B = [[9, 8, 7, 6],
[5, 4, 3, 2],
[1, 0, -1, -2]]
# Create a matrix to hold the result
C = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
# Multiply matrices A and B and store the result in C
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j] += A[i][k] * B[k][j]
# Display the resulting matrix C
for row in C:
print(row)
Explanation:
The matrices A and B are defined as 3x3 and 3x4 lists of lists, respectively.
A matrix C is created as a 3x4 list of lists initialized to all zeros.
The matrices A and B are multiplied using a nested for loop that iterates over the rows and columns of the resulting matrix C. For each element at position (i, j) in C, the corresponding element is calculated by summing the products of the elements in the ith row of A and the jth column of B.
The resulting matrix C is displayed using a for loop that iterates over the rows of the matrix and prints each row.
For Example:
[22, 16, 10, 4]
[67, 52, 37, 22]
[112, 88, 64, 40]