[Numpy-discussion] Finding indices and setting values

Perry Greenfield perry at stsci.edu
Wed May 21 08:42:07 CDT 2003


>
> I have a problem where I want to set values in a 2D array based on
> conditions I’ve established. The variables are the NA of the system, its
> wavelength and the correct units on the device I’m modeling. Using these
> variables I define a variable N. I set up a 512 by 512 array [x,y]. Then
> I set up a radius , r = x^2 +y^2 and ask it to give me all r’s(to the
> closest integer) <= N(the variable I’ve defined above). This gives all
> the index values in that radius and then I set all those locations to a
> value of 1. After this I do some FFT ‘s, etc. So how do I do this in
> Numerical Python without having to index through i,j steps which would
> be incredibly tedious. This works fairly well in MatLab but I want to
> port my program to Python(for lots of reasons). If you’d rather I write
> the MatLab code snippet I can do that. Thanks.
>
> Cliff Martin
>
One way should be something like this (I haven't tested this)
This only works in numarray. If data is the 2-d array where you
want to set values within a radius of N (of x0, y0 I presume)

y, x = indices(data.shape)
data[nonzero(((x-x0)**2+(y-y0)**2) < N**2)] = 1

(in a future version of numarray this will also work and the meaning
should be clearer: data[where(((x-x0)**2+(y-y0)**2) < N**2)] = 1

It's a little more involved for Numeric but still possible to do
without resorting to loops (I'll leave it to someone else to
show that).

Does this do what you wanted?

Perry Greenfield.





More information about the Numpy-discussion mailing list