+ 1
How to print an error message for matrices of incompatible sizes. Like after testing a compatible matrice of multiplication
I don't know where to input the error code if the matrices are not compatible # take a 2x2 matrix A = [ [3, -1], [1,2] ] # take a 2x2 matrix B = [ [1,4], [2, -3] ] result = [ [0,0], [0,0] ] # iterating by row of A for i in range(len(A)): # iterating by column by B for j in range(len(B[0])): # iterating by rows of B for k in range(len(B)): result[i][j] += A[i][k] * B[k][j] for r in result: print(r)
5 Respuestas
+ 1
Umar Akorede
# take a 2x2 matrix
A = [ [3, -1], [1,2] ]
# take a 2x2 matrix
B = [ [1,4]]
result = [ [0,0], [0,0] ]
#check length of a and b
if len(A) == 2 and len(B) == 2:
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
else:
print("Matrix is not 2x2!")
Here,this will print out an error because B is not 2x2
0
Umar Akorede
Well you're taking a 2x2 matrix right? Then just do an if statement above the first for loop if the length of matrix a and b is == 2 then run it,else print out an error message
0
raynard can you kindly copy my code and input what you mean. I don't seem to get it. Thanks
0
raynard thanks mate!
0
Umar Akorede no problem🤝