[SciPy-user] Replacing elements in matrix

David M. Cooke cookedm at physics.mcmaster.ca
Tue Apr 26 12:42:11 CDT 2005

steve schmerler <elcorto at gmx.net> writes:

> 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.  With this operation, some of the elements
>> of A are replaced by their original value augmented by some value
>> coming from B.  for example, take
>> 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]])  With this, Matlab results would
>> be A[indexi,indexj]=array([[5, 7, 2],[4, 6, 2]]) and
>> A[indexi,indexj]=A[indexi,indexj]+B yields
>> A=array([[1,15,27,8,32],[5,3,4,6,7],[9,104,206,7,302],[0,2,0,3,4]])
>> I would like to make the same operation with Python. Would you
>> please propose me a compact code for achieving that?
> Hmm, I'm affraid this isn't straightforward. To select arbitrary rows and cols from A you can use
> Numeric's take()
> 	In [10]: take(take(A,(0,2),axis=0),(1,2,4),axis=1)
> 	Out[10]:
> 	array([[5, 7, 2],
>         	       [4, 6, 2]])
> but any operation on the selected submatrix won't alter A.

> With slicing, e.g. select the upper 2x2 block
> 	In [14]: A[0:2,0:2]
> 	Out[14]:
> 	array([[1, 5],
>                 [5, 3]])
> you also can't alter A by performing some operation on the subblock, e.g.

eh? No, a slice is a view of the matrix, so it also operates on the
original matrix.

> 	A[0:2,0:2]*100
> doesn't change A.

Of course, that doesn't change an array at all (you'll get a new 2x2
matrix). This will:

A[0:2,0:2] *= 100

That'll change the submatrix A[0:2,0:2], and A.

> Btw, I don't know how to select _arbitrary_ rows and cols with slicing (hints?).

You mean, say, the i'th row? That's A[i]. If you need an arbitrary
selection of rows, you're out of luck as far as making one matrix
that's a view of A (but you can make a copy as you did above with take()).

|David M. Cooke                      http://arbutus.physics.mcmaster.ca/dmc/
|cookedm at physics.mcmaster.ca

More information about the SciPy-user mailing list