Home > Blockchain >  Python Matrix multiplication using for loop
Python Matrix multiplication using for loop

Time:04-01

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.

CodePudding user response:

To access an inner array, you use this syntax:

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

CodePudding user response:

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.

  • Related