0
votes

Im trying to ensure each row has zero mean for a matrix of arbitrary dimensions. However Im getting IndexError: index 2 is out of bounds for axis 0 with size 2 when running the code below. Im iterating over values within the dimensions of Z only so I don't see how I could be attempting to index outside the dimensions of Z.

import numpy as np

def center_rows(Z):
     """Ensures each row has zero mean.
       Takes a matrix of arbitrary shape and subtracts from each row   the mean value of that row."""
 Zc = Z

 for row in Z:
     avg = np.mean(Z[row])
     Zc[row] = Z[row] - avg

 return Zc
1
Say, Z = [[1,2,3], [4,5,6]]. The first row == [1,2,3]. Does Z[row] make sense? It may make sense for multidimensional NumPy arrays, but is it what you really want? - ForceBru
I tried changing it to for row in range(len(Z)) instead but it doesen't fix anything. - user9231414
please post Z, and fix indentation. - Kenny Ostrom

1 Answers

0
votes

Just a thought but usually you don't want to use python loops over Numpy arrays. You could get rows with 0 mean using just Numpy which would ideally skip the loop

Z - np.mean(Z,axis = 1)[:,None]

Also I'm not the most informed about how things work but Zc = Z may just point to the same array. At least when I tested it modifying either one modified the other so maybe adding.

Zc = Z.copy()

would help.

Edit: [:,None] just adds an extra dimension to the mean array. You can test it easily.

import numpy as np

test = np.array([1,2,3])

test.shape
Out[3]: (3,)

test[:,None].shape
Out[4]: (3, 1)

By having the same number of dimensions you can subtract the means directly from the array without the for loop.