Multiplication of two matrices in python¶
In [1]:
m = int (input('Enter the number of rows of the first matrix: '))
n = int (input('Enter the number of columns of the first matrix: '))
p = int (input('Enter the number of rows of the second matrix: '))
q = int (input('Enter the number of columns of the second matrix: '))
if n != p:
print ('Multiplication is not possible, because the number columns of the first matrix and the number of rows of the second matrix is not same')
else:
print ('Multiplication is possible: ')
A = []
print ('Enter the elements of the first matrix: ')
for i in range(0, m):
r = []
for j in range(0, n):
r.append(int (input()))
A.append(r)
B = []
print ('Enter the elements of the second matrix: ')
for i in range(0, p):
r = []
for j in range(0, q):
r.append(int (input()))
B.append(r)
#Assign value of each elements of the result matrix
mul = []
for i in range(0, m):
x = []
for j in range(0, q):
x.append(0)
mul.append(x)
# Applying multiplication formula
for i in range(0, m):
for j in range(0, q):
for k in range(0, n):
mul[i][j] = mul[i][j] + (A[i][k] * B[k][j])
print ('First matrix is: ')
for i in range(0, m):
for j in range(0, n):
print(A[i][j], end = " ")
print()
print ('Second matrix is: ')
for i in range(0, p):
for j in range(0, q):
print(B[i][j], end = " ")
print()
print ('Multiplication of the two marix is: ')
for i in range(0, m):
for j in range(0, n):
print(mul[i][j], end = " ")
print()
Enter the number of rows of the first matrix: 2 Enter the number of columns of the first matrix: 3 Enter the number of rows of the second matrix: 3 Enter the number of columns of the second matrix: 4 Multiplication is possible: Enter the elements of the first matrix: 2 3 4 3 4 5 Enter the elements of the second matrix: 3 4 5 6 2 3 4 5 1 2 3 4 First matrix is: 2 3 4 3 4 5 Second matrix is: 3 4 5 6 2 3 4 5 1 2 3 4 Multiplication of the two marix is: 16 25 34 22 34 46
Thank you very much!! I am searching this solution for a long time.
ReplyDelete