numpy/matlab compatibility
Robert Kern
robert.kern at gmail.com
Tue Jan 25 17:21:43 EST 2011
On 1/25/11 2:13 PM, Matt Funk wrote:
> Hi,
>
> i am fairly new to python. I was wondering of the following is do-able
> in python:
>
> 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)
You will want to ask numpy questions on the numpy-discussion mailing list
instead of here.
http://www.scipy.org/Mailing_Lists
When asking how to replicate a particular MATLAB behavior, please describe (and
preferably also *show*) what the given MATLAB code does. We're not all familiar
with MATLAB, and even if we are, we may not know which specific aspect of the
code you want us to replicate.
You will also want to check out this page:
http://www.scipy.org/NumPy_for_Matlab_Users
To answer your specific questions:
1) a = numpy.random.random_sample([10, 1])
2) Y = a.copy()
# In Python assignment to a new name does not copy the object. You seem to
want a copy in this case. numpy arrays have a .copy() method, though most Python
objects don't.
3) mask = Y > 0.5
# Note that Y only has values in [0..1) at this point, so using 100 here will
create a boolean mask with only False entries. This is probably not what you
wanted to show, so I used 0.5 instead.
4) Y[mask] = 100
5) a = a + Y
# Or "a += Y" if you want to modify "a" in-place.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list