[SciPy-user] Replacing elements in matrix

Stephen Walton stephen.walton at csun.edu
Tue Apr 26 12:15:56 CDT 2005

```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,).

```