Matlab-style mask in Python??
Chris Barker
chrishbarker at home.net
Tue Oct 30 21:01:49 CET 2001
Ozone Hole near South Pole <ozonehole2k at yahoo.com> wrote:
| I am a long time Matlab user. I just picked up Python for a short
| while.
| I wonder what should be the best way to do sth like:
| Matlab:
| a=[3,4,6,7,2,54,2,1,2]
| idx=a>4 ans: [0,0,1,1,0,1,0,0,0]
| a(idx) ans: [6,7,54]
| Python:
| a=[3,4,6,7,2,54,2,1,2]
| idx=map(lambda x: x>4,a) #assume this calculation is lengthy
| #and we don't want to repeat
| last cmd???
have a look at Numerical Python http://www.numpy.org. I think it
will help you.
It absolutely will:
>>> from Numeric import *
>>> a=array([3,4,6,7,2,54,2,1,2])
>>> a
array([ 3, 4, 6, 7, 2, 54, 2, 1, 2])
>>> idx = a > 4
>>> idx
array([0, 0, 1, 1, 0, 1, 0, 0, 0])
>>> take(a,nonzero(idx))
array([ 6, 7, 54])
Numeric has most of the basic functionality that MATLAB does, but a much
smaller library of extras. The SciPy (www.scipy.org) project is working
to addess this.
Numeric also lacks MATLAB'S nifty array indexing and mask indexing. Note
how I used take and nonzero above. This does make code littel more
verbose, but Numeric has a number of advantages as well. Consider "array
broadcasting":
>>> x = arange(5)
>>> x.shape = (1,-1) # make it a row vector, the -1 means use whatever fits.
>>> x
array([ [0, 1, 2, 3, 4]])
>>> y = arange(3)
>>> y.shape = (-1,1) # make it a column vector
>>> y
array([[0],
[1],
[2]])
>>> z = x*y
>>> z
array([[0, 0, 0, 0, 0],
[0, 1, 2, 3, 4],
[0, 2, 4, 6, 8]])
In Matlab, you would have had to create an entire array of X and Y with
[X,Y] = meshgrid(x,y)
Which is a whole lot clunkier, and wastes a lot of memory.
All in all, I like NumPy better. (and I like MATLAB a lot)
-Chris
--
Christopher Barker,
Ph.D.
ChrisHBarker at home.net --- --- ---
http://members.home.net/barkerlohmann ---@@ -----@@ -----@@
------@@@ ------@@@ ------@@@
Oil Spill Modeling ------ @ ------ @ ------ @
Water Resources Engineering ------- --------- --------
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------
More information about the Python-list
mailing list