0

This code throws an exception:

"list index out of range"

at the line marked below.

col_sig_squared = [np.zeros(shape=(1,6), dtype=int)]

def calculate_col_sigma_square(matrix):
    mx = np.asarray(matrix)
    for(x,y), value in np.ndenumerate(matrix):
    if(x > 4):
            continue
    else:
        val = matrix[x][y] - x_bar_col[x]
        val = val**2
        EXCEPTION-->print col_sig_squared[y] 

Why is this a problem? col_sig_squared is an array with indices. Why can't I access it like this. Tried a bunch of things but not sure why this syntax is wrong. I'm new to Python and its intricacies, any help would be appreciated.

Thanks

1
  • 1
    Generally don't use matrix[x][y] use matrix[x,y] there is a big difference if x is not a scalar. Commented Oct 24, 2012 at 21:18

2 Answers 2

1

Well, the message tells you what is wrong pretty clearly. y is bigger at that point than the number of items in col_sig_squared. This doesn't surprise me because col_sig_squared is defined as a list with one item, a NumPy array:

col_sig_squared = [np.zeros(shape=(1,6), dtype=int)]

This means that only col_sig_squared[0] is valid.

Maybe you meant:

col_sig_squared = np.zeros(shape=(1,6), dtype=int)

Now col_sig_squared is a NumPy array.

Sign up to request clarification or add additional context in comments.

Comments

0

It is more common to express NumPy array vectors using shape = (N,). For instance:

>>> col_sig_1byN = np.zeros(shape=(1,6), dtype=int)
>>> col_sig_N = np.zeros(shape=(6,), dtype=int)
>>> print col_sig_1byN
[[0 0 0 0 0 0]]
>>> print col_sig_N
[0 0 0 0 0 0]

You can index col_sig_N as col_sig_N[p], but for col_sig_1byN you have to do col_sig_1byN[0,p] - note that [x,y] is the way to index into a multidimensional NumPy array.

To index a whole row/column you can do [x,:]/[:,y].

And, as kindall said, you should not embed your array in a list.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.