asapsav
asapsav

Reputation: 1

Python Matrix multiplication using for loop

from numpy import linalg
from numpy import matmul



M = [[2,1],[1,3]]
b = [[3],[-1]
Mb = [] 

nrows = 2
ncols = 2
for i in range(0,nrows):
    sum = 0
    for j in range(0,ncols):
        sum = sum + M[i,j] * b[j]
     Mb[?] = ?   

print(Mb)

#the goal of this was to multiply matrices using a loop. I keep getting the error (python list indices must be integers not tuple) when trying to run this. I'm not sure what I need to put in place of the question marks inserted.

Upvotes: 0

Views: 479

Answers (2)

blarg
blarg

Reputation: 349

The issue is in this array indexing: M[i,j]. Built-in nested (not truly multi-dimensional) python arrays cannot be accessed in this way, you must index the dimensions one at a time: M[i][j].

You may see python code that does use this indexing, but that is with 3rd party libraries such as numpy.

Upvotes: 1

jozborn
jozborn

Reputation: 39

To access an inner array, you use this syntax:

sum = sum + M[i][j] * b[j]

Upvotes: 0

Related Questions