# [SciPy-user] Replacing elements in matrix

steve schmerler elcorto at gmx.net
Tue Apr 26 12:31:09 CDT 2005

```Hi

A=array([[1,5,7,8,2],[5,3,4,6,7],[9,4,6,7,2],[0,2,0,3,4]])
indexi=array([[0,0,0],[2,2,2]])
indexj=array([[1,2,4],[1,2,4]])

but get

In [8]: A[indexi,indexj]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)

C:\Dokumente und Einstellungen\user\Eigene Dateien\<console>

IndexError: each subindex must be either a slice, an integer, Ellipsis, or NewAxis

Am I missing something here??

Cheers,
Steve

Stephen Walton wrote:
> Dimitri D'Or wrote:
>
>> Hello,
>> I come from the Matlab world and I'm used to write operations such as:
>> A[indexi,indexj]=A[indexi,indexj]+B where A is a n by n matrix, indexi
>> is i by 1 vector, indexj is a j by 1 vector and B is a i by j matrix.
>
>
> Novice alert here, but I think I can partially answer this one.  The key
> idea is that Numeric and numarray indexing require indexi and indexj to
> have the same number of elements.  A[indexi,indexj] then returns an
> array containing A[indexi[0],indexj[0]],A[indexi[1],indexj[1]],...].
> This is if indexi and indexj are rank 1 arrays.  The indexing takes a
> "hint" from the shape of indexi and indexj and returns the same shape
> output (that's the best way I've been able to put it).
>
> A=array([[1,5,7,8,2],[5,3,4,6,7],[9,4,6,7,2],[0,2,0,3,4]])
> indexi=array([0,2]) indexj=array([1,2,4])
> B=array([[10,20,30],[100,200,300]])
>
> The definitions of indexi and indexj should actually be:
>
> indexi=array([[0,0,0],[2,2,2]])
> indexj=array([[1,2,4],[1,2,4]])
>
> With this change
>
> A[indexi,indexj]=A[indexi,indexj]+B
>
> does work.  Notice that becase indexi.shape and indexj.shape are both
> (2,3), the output A[indexi,indexj] has shape (2,3).  If they both had
> shape (6,), then A[indexi,indexj] would also have shape (6,).
>
> _______________________________________________
> SciPy-user mailing list
> SciPy-user at scipy.net
> http://www.scipy.net/mailman/listinfo/scipy-user
>
>

--
Man is the best computer we can put aboard a spacecraft ... and the only one that can be
mass produced with unskilled labor.  - Wernher von Braun

```