Write a program to multiply two matrix


Topic: Write a program to multiply two matrix

Solution

rowsA = len(A)
colsA = len(A[0])
rowsB = len(B)
colsB = len(B[0])
if colsA != rowsB:
    raise ArithmeticError('Number of A columns must equal number of B rows.')
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):
        total = 0
        for ii in range(colsA):
            total += A[i][ii] * B[ii][j]
        C[i][j] = total
print("Multiplied Array")
for i in range(rowsA):
    row = '|'
    for b in range(colsA):
        row = row + ' ' + str(C[i][b])
    print(row + ' ' + '|')



List all Python Programs