1

I have to check if the given matrices can be multiplied, and if yes, return the product. I cannot use numpy to calculate the product.

Example used:

A = [[1,2],[3,4]]
B = [[1,2,3,4,5],[5,6,7,8,9]]

Expected output: A*B = [[11,14,17,20,23],[23,30,37, 44,51]]

Here's my code and output:

def matrix_mult(A,B):
    countA = 0
    countB = 0
    result = [[0]*len(B[0])]*len(A)
    for i in range(len(A)):
        if A[i][1]:
            countA += 1

    for i in range(len(B)):
        if B:
            countB += 1

    if countA == countB:
        for i in range(len(A)):
            for j in range(len(B[0])):
                for k in range(len(A)):
                    result[i][j] += A[i][k]*B[k][j]

    return result

A = [[1,2],[3,4]]
B = [[1,2,3,4,5], [5,6,7,8,9]]
matrix_mult(A,B)

output:

[[34, 44, 54, 64, 74], [34, 44, 54, 64, 74]]

Is there something wrong with the code/logic?

Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
Deven Bothra
  • 78
  • 1
  • 9

3 Answers3

2

The guilty is your result declaration. It's not a good way to declare a list by duplicating the elements (not creating a proper matrix). More details in this discussion.

Try:

result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]

Instead of:

result = [[0] * len(B[0]) ] * len(A)

And that should work fine !

Alexandre B.
  • 5,387
  • 2
  • 17
  • 40
1

Why make the code so long? You can try this -

def dot(A, B):
    return [[sum(x*y for x, y in zip(A_row, B_column)) for B_column in zip(*B)] for A_row in A]

A = [[1,2],[3,4]]
B = [[1,2,3,4,5],[5,6,7,8,9]]
result = dot(A, B)
print(result)

#[[11, 14, 17, 20, 23], [23, 30, 37, 44, 51]]

See if this helps you.

Justin
  • 1,006
  • 12
  • 25
1

I will recommend using numpy:

import numpy as np

A = np.array([[1,2],[3,4]])
B = np.array([[1,2,3,4,5],[5,6,7,8,9]])

np.matmul(A, B)

# output : array([[11, 14, 17, 20, 23],
#                 [23, 30, 37, 44, 51]])

with your code there are several issues, below I was trying to improve your code:

def matrix_mult(A,B):

    num_col_a = len(A[0])
    num_rows_b = len(B)

    result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]

    if num_col_a == num_rows_b:
        for row_a_index, row_a in enumerate(A):
            for col_index, col_b in enumerate(zip(*B)):
                result[row_a_index][col_index] = sum(a * b for a, b in zip(row_a, col_b))

    return result

A = [[1,2],[3,4]]
B = [[1,2,3,4,5], [5,6,7,8,9]]
print(matrix_mult(A,B))

# output: [[11, 14, 17, 20, 23], [23, 30, 37, 44, 51]]
kederrac
  • 16,819
  • 6
  • 32
  • 55