[SciPy-user] Replacing elements in matrix
elcorto at gmx.net
Tue Apr 26 10:31:48 CDT 2005
Dimitri D'Or wrote:
> I come from the Matlab world and I'm used to write operations such as:
> 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
> With this, Matlab results would be
> A[indexi,indexj]=array([[5, 7, 2],[4, 6, 2]])
> A[indexi,indexj]=A[indexi,indexj]+B yields
> 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
In : take(take(A,(0,2),axis=0),(1,2,4),axis=1)
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 : A[0:2,0:2]
you also can't alter A by performing some operation on the subblock, e.g.
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
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