Skip to content Skip to sidebar Skip to footer

How To Multiply Two Matrices Together In Python

I am trying to multiply to matrices together using only Python. To keep it simple, we'll say that they will always be the same size. I have tried so many different ways, but haven'

Solution 1:

I would recommend numpy for this task however here is something that should work:

defmulti(x,y):
    d = []
    i = 0while i < len(x):
        j = 0
        e = []
        while j < len(y[0]):
            k = 0
            r = 0while k < len(x[0]):
                r += x[i][k] * y[k][j]
                k += 1
            j += 1
            e.append(r)
        d.append(e)
        i += 1print(d)

Solution 2:

If you don't wish to use NumPy, maybe you'll find this code helpful:

defmatprod(x, y):
    I = range(len(x))
    J = range(len(y[0]))
    K = range(len(x[0]))
    return [[sum(x[i][k]*y[k][j] for k in K) for j in J] for i in I]

Although is close to the mathematical notation used to define matrix multiplication, the code above is not quite readable. To improve readability you could use the approach proposed in this answer.

Post a Comment for "How To Multiply Two Matrices Together In Python"