sten33
sten33

Reputation: 1

multiplication in Python matrices

I'm trying to multiply two matrices but I'm having difficulties with my code:

def multiply(a,b):
    mul=[[]]
    for x in range(0,len(a)):
        for n in range(0,len(a[0])):
            mul[x][n]+=a[x][n]*b[x][n]
    mul.append(mul[x][n])
    for n in mul:
        return mul

a= [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
b= [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
multiply(a,b)

hypothetically, I'm trying to keep the mul variable within bounds as my for functions iterate through a and b but I'm not sure why it's not working out.

Would you guys have any suggestions?

Upvotes: 0

Views: 87

Answers (2)

Daniel Giger
Daniel Giger

Reputation: 2553

There are a few issues. First, you need to initialize mul with the right dimensions, as @jasonharper pointed out. I used a list comprehension for this.

Second, you actually need 3 loops to be able to do matrix multiplication like this.

Third, a for loop with an unconditional return will only run once, so you might as well replace the last loop with return mul.

Fourth, the matrices you're trying to multiply are not compatible, since they're both 4x3. The number of columns in a needs to be the same as the number of rows in b.

Here's a working version:

def multiply(a,b):
    mul= [[0] * len(b[0]) for _ in range(len(a))]
    for x in range(len(a)):
        for n in range(len(b[0])):
            for pos in range(len(a[0])):
                mul[x][n] += a[x][pos] * b[pos][n]
    return mul

Upvotes: 1

morallito
morallito

Reputation: 129

It's more easy work with numpy matmul function to do this. Try:

import numpy as np

a =np.array([[2, 2], [2, 2]])
b =np.array([[2, 2], [2, 2]])

c = np.matmul(a,b)

print(c)

Upvotes: 1

Related Questions