1

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't figured it out. Here are the two matrices:

matrix_a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
matrix_b = [[3, 2, 1], [3, 2, 1], [3, 2, 1]]
Tonechas
  • 13,398
  • 16
  • 46
  • 80
Jaromjj
  • 326
  • 3
  • 17
  • 1
    you should better use numpy for this kind of tasks. http://www.numpy.org/ – marmeladze May 14 '16 at 22:14
  • 1
    I personally like questions like this one a lot (can't understand the downvote), because they show the desire to understand the idea of say a matrix multiplication before optimizing things with numpy. I use numpy a lot but many of the numpy questions show that people have not even tried to understand their own data (often the wrong dimension) or care about the inner workings, which leads to test-free, superficial, low quality code. – roadrunner66 May 14 '16 at 22:22
  • @roadrunner66: though none of the downvotes were mine, one of the criteria for a DV (you can see it if you hover over the downvote arrow) is "does not show any research effort". This question shows no research effort whatsoever. – DSM May 15 '16 at 02:31
  • @DSM, fair point. There is a difference between questions where the answers are obvious (some would call them dumb), where a downvote is really not justified (we all had such questions ourselves) and the ones that lack effort. – roadrunner66 May 15 '16 at 04:01

2 Answers2

5

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

def multi(x,y):
    d = []
    i = 0
    while i < len(x):
        j = 0
        e = []
        while j < len(y[0]):
            k = 0
            r = 0
            while k < len(x[0]):
                r += x[i][k] * y[k][j]
                k += 1
            j += 1
            e.append(r)
        d.append(e)
        i += 1
    print(d)
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
1

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

def matprod(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.

Tonechas
  • 13,398
  • 16
  • 46
  • 80