Python code to Compute the Product of Two Matrices.
Python code implementation without user-defined functions & classes
Code:
#Python code to Compute the Product of Two Matrices
a = [[1, 2, 3]]
b = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
a_row_size = len(a)
a_column_size = len(a[0])
b_row_size = len(b)
b_column_size = len(b[0])
c = [[0, 0, 0]]
print(a_row_size)
print(a_column_size)
print(b_row_size)
print(b_column_size)
if a_column_size == b_row_size:
print("Matrix Multiplication is Possible: ")
else:
print("Matrix Multiplication not Possible: ")
exit()
for i in range(0, a_row_size):
for j in range(0, b_row_size):
for k in range(0, b_column_size):
c[i][j] = c[i][j] + a[i][k] * b[k][j]
print("Result after Multiplication: ",c)
Output:
1 3 3 3 Matrix Multiplication is Possible: Result after Multiplication: [[30, 36, 42]]
Python code implementation using function
Code:
#Python code to Compute the Product of Two Matrices using function
a = [[1, 2, 3]]
b = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
def matrix_product_function(matrix_a, matrix_b):
a_row_size = len(matrix_a)
a_column_size = len(matrix_a[0])
b_row_size = len(matrix_b)
b_column_size = len(matrix_b[0])
c = [[0, 0, 0]]
print(a_row_size)
print(a_column_size)
print(b_row_size)
print(b_column_size)
if a_column_size == b_row_size:
print("Matrix Multiplication is Possible: ")
else:
print("Matrix Multiplication not Possible: ")
exit()
for i in range(0, a_row_size):
for j in range(0, b_row_size):
for k in range(0, b_column_size):
c[i][j] = c[i][j] + matrix_a[i][k] * matrix_b[k][j]
return c
print("Result after Multiplication: ",matrix_product_function(a,b))
Output:
1 3 3 3 Matrix Multiplication is Possible: Result after Multiplication: [[30, 36, 42]]
Python code implementation using Classes
Code:
#Python code to Compute the Product of Two Matrices using class
a = [[1, 2, 3]]
b = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
class Matrix_product_class(object):
def matrix_product_function(self, matrix_a, matrix_b):
self.matrix_a = matrix_a
self.matrix_b = matrix_b
a_row_size = len(self.matrix_a)
a_column_size = len(self.matrix_a[0])
b_row_size = len(self.matrix_b)
b_column_size = len(self.matrix_b[0])
c = [[0, 0, 0]]
print(a_row_size)
print(a_column_size)
print(b_row_size)
print(b_column_size)
if a_column_size == b_row_size:
print("Matrix Multiplication is Possible: ")
else:
print("Matrix Multiplication not Possible: ")
exit()
for i in range(0, a_row_size):
for j in range(0, b_row_size):
for k in range(0, b_column_size):
c[i][j] = c[i][j] + self.matrix_b[i][k] * self.matrix_b[k][j]
return c
#Creating Object
Object_1 = Matrix_product_class()
#Calling Function using created object
print("Result after Multiplication: ",Object_1.matrix_product_function(a,b))
Output:
1 3 3 3 Matrix Multiplication is Possible: Result after Multiplication: [[30, 36, 42]]
Enjoy Python Code By Pythonbaba 🙂