Mustard Tiger
Mustard Tiger

Reputation: 3671

Python matrix indexing

I have the following code

l = len(time)     #time is a 300 element list
ll = len(sample)  #sample has 3 sublists each with 300 elements

w, h = ll, l 
Matrix = [[0 for x in range(w)] for y in range(h)]

for n in range(0,l):

    for m in range(0,ll):

        x=sample[m]
        Matrix[m][n]= x

When I run the code to fill the matrix I get an error message saying "list index out of range" I put in a print statement to see where the error happens and when m=0 and n=3 the matrix goes out of index.

from what I understand on the fourth line of the code I initialize a 3X300 matrix so why does it go out of index at 0X3 ?

Upvotes: 1

Views: 3664

Answers (3)

Madhav Datt
Madhav Datt

Reputation: 1083

Note that indexing in nested lists in Python happens from outside in, and so you'll have to change the order in which you index into your array, as follows:

Matrix[n][m] = x

For mathematical operations and matrix manipulations, using numpy two-dimensional arrays, is almost always a better choice. You can read more about them here.

Upvotes: 1

Blckknght
Blckknght

Reputation: 104712

The indexing of nested lists happens from the outside in. So for your code, you'll probably want:

Matrix[n][m] = x

If you prefer the other order, you can build the matrix differently (swap w and h in the list comprehensions).

Note that if you're going to be doing mathematical operations with this matrix, you may want to be using numpy arrays instead of Python lists. They're almost certainly going to be much more efficient at doing math operations than anything you can write yourself in pure Python.

Upvotes: 2

vishes_shell
vishes_shell

Reputation: 23484

You need to change Matrix[m][n]= x to Matrix[n][m]= x

Upvotes: 4

Related Questions