Saturday, February 9, 2019

Matrix Multiplication Example

This program creates 2 matrices with random elements between 0 and 9. After creating the matrices it multiplies and prints the final matrix. You can modify it to input matrices from users.

Code:

import random, sys
m = int(input("Enter number of rows for 1st matrix: "))
n = int(input("Enter number of columns for 1st matrix: "))
p = int(input("Enter number of rows for 2nd matrix: "))
q = int(input("Enter number of columns for 2nd matrix: "))
if n != p:
print("Cannot multiply the given matrices.")
print("No. of rows of 1st matrix must match columns of 2nd.")
sys.exit(0)
mat1 = [[random.randint(0,9) for x in range(n)] for y in range(m)]
mat2 = [[random.randint(0,9) for x in range(q)] for y in range(p)]
prod = [[0 for x in range(q)] for y in range(m)]
print("Matrix 1:")
for x in mat1:
print(x)
print("Matrix 2:")
for x in mat2:
print(x)
for i in range(m):
for j in range(q):
for k in range(n):
prod[i][j] += mat1[i][k] * mat2[k][j]
print("Product of matrices:")
for x in prod:
print(x)

No comments: