Write a program to subtract two matrix


Topic: Write a program to subtract two matrix

Solution

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rowsA = len(A)
colsA = len(A[0])
rowsB = len(B)
colsB = len(B[0])
if rowsA != rowsB or colsA != colsB:
    raise ArithmeticError('Matrices are NOT the same size.')
C = []
while len(C) < rowsA:
    C.append([])
    while len(C[-1]) < colsB:
        C[-1].append(0.0)
for i in range(rowsA):
    for j in range(colsB):
        C[i][j] = A[i][j] - B[i][j]
print("Subtracted Array")
for i in range(rowsA):
    row = '|'
    for b in range(colsA):
        row = row + ' ' + str(C[i][b])
    print(row + ' ' + '|')



List all Python Programs