How about a little programming session today?
Develop a program to read in 2 matrices A and B with dimensions (l X m) and (m X n) respectively, and compute and display their product AB(of dimensions (l X n)). Assume that the elements of matrices are integers. An example is shown below.(l,m,n belongs to positive integers)
Matrix A:
1 2 5
2 1 6
Matrix B:
3 4 6 4
5 6 1 2
7 8 9 9
Matrix AB:
48 56 53 53
53 62 67 64
We recommend you to tryout the question before you check the answer.
Here is a Python code for above question.
r1,c1=input("input first matrix rows and columns:").split(" ")
m1=[]
for p in range(0,int(r1)):
m1.append(list(map(int,input().split(" "))))
r2,c2=input("input second matrix rows and columns:").split(" ")
m2=[]
for q in range(0,int(r2)):
m2.append(list(map(int,input().split(" "))))
if c1!=r2:
print("invalid input")
else:
m3=[]
t=0
for i in range(0,int(r1)):
for j in range (0,int(c2)):
for k in range(0,int(r2)):
t=m1[i][k]*m2[k][j]+t
m3.append(t)
print(t,end=" ")
t=0
print("\n",end="")
Develop a program to read in 2 matrices A and B with dimensions (l X m) and (m X n) respectively, and compute and display their product AB(of dimensions (l X n)). Assume that the elements of matrices are integers. An example is shown below.(l,m,n belongs to positive integers)
Matrix A:
1 2 5
2 1 6
Matrix B:
3 4 6 4
5 6 1 2
7 8 9 9
Matrix AB:
48 56 53 53
53 62 67 64
We recommend you to tryout the question before you check the answer.
Here is a Python code for above question.
r1,c1=input("input first matrix rows and columns:").split(" ")
m1=[]
for p in range(0,int(r1)):
m1.append(list(map(int,input().split(" "))))
r2,c2=input("input second matrix rows and columns:").split(" ")
m2=[]
for q in range(0,int(r2)):
m2.append(list(map(int,input().split(" "))))
if c1!=r2:
print("invalid input")
else:
m3=[]
t=0
for i in range(0,int(r1)):
for j in range (0,int(c2)):
for k in range(0,int(r2)):
t=m1[i][k]*m2[k][j]+t
m3.append(t)
print(t,end=" ")
t=0
print("\n",end="")
Comments
Post a Comment