Algorithm


  1. Input:

    • Read the dimensions of the first matrix (m1 x n1) and the second matrix (m2 x n2).
    • Ensure that the number of columns in the first matrix (n1) is equal to the number of rows in the second matrix (m2) for valid multiplication.
  2. Initialize Result Matrix:

    • Create an empty matrix result of size m1 x n2, where m1 is the number of rows in the first matrix, and n2 is the number of columns in the second matrix.
    • Initialize all elements of the result matrix to zero.
  3. Matrix Multiplication:

    • Use nested loops to iterate through each element of the result matrix.
    • For each element result[i][j], calculate the sum of the product of corresponding elements from the ith row of the first matrix and the jth column of the second matrix.
      python
      for i in range(m1): for j in range(n2): for k in range(m2): result[i][j] += matrix1[i][k] * matrix2[k][j]
  4. Output:

    • Print or return the resulting matrix result

 

Code Examples

#1 Code Example- Matrix Multiplication using Nested Loop

Code - Python Programming

# Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
         [0,0,0,0],
         [0,0,0,0]]

# iterate through rows of X
for i in range(len(X)):
   # iterate through columns of Y
   for j in range(len(Y[0])):
       # iterate through rows of Y
       for k in range(len(Y)):
           result[i][j] += X[i][k] * Y[k][j]

for r in result:
   print(r)
Copy The Code & Try With Live Editor

Output

x
+
cmd
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

#2 Code Example- Matrix Multiplication Using Nested List Comprehension

Code - Python Programming

# Program to multiply two matrices using list comprehension

# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]

# result is 3x4
result = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in X]

for r in result:
   print(r)
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Python Programing to Multiply Two Matrices-DevsEnv