numpy/matlab compatibility
Nicholas Devenish
misnomer at gmail.com
Tue Jan 25 17:03:20 EST 2011
On 25/01/2011 20:13, Matt Funk wrote:
> 1) a = rand(10,1)
> 2) Y = a
> 3) mask = Y> 100;
> 4) Y(mask) = 100;
> 5) a = a+Y
>
> Basically i am getting stuck on line 4). I was wondering if it is
> possible or not with python?
> (The above is working matlab code)
I don't understand this matlab code completely (I would expect rand to
return in the range 0-1, so would expect (Y > 100) to match nothing).
Nonetheless, to achieve line 4 I believe you are looking for:
>>> Y[mask] = 100
However, you can also do directly:
>>> Y[Y>100] = 100
This won't work exactly as you anticipate, because presumably in matlab
the line 'Y = a' makes a copy of 'a' (it has been a long time since I
used matlab). In python, Y and a will still refer to the same object, so
altering Y will also alter a. The *most literal* translation to python
of your sample is probably:
>> import numpy
>> a = numpy.random.rand(10,1)
>> Y = a.copy()
>> mask = Y > 100
>> Y[mask] = 100
>> a = a + Y
More information about the Python-list
mailing list