[SciPy-user] Replacing elements in matrix

steve schmerler elcorto at gmx.net
Tue Apr 26 11:31:48 EDT 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. 
>  
> 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.
	
	A[0:2,0:2]*100

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

Try to play arround with Numeric's take(), put() (or putmask()) functions. Sry but I don't have any cool elegant idea at 
the moment.

Cheers,
Steve


-- 
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




More information about the SciPy-User mailing list