calculating on matrix indices

Robert Kern robert.kern at gmail.com
Thu Feb 16 22:27:56 EST 2006


Brian Blais wrote:
> Colin J. Williams wrote:
> 
>> Brian Blais wrote:
>>
>>> In my attempt to learn python, migrating from matlab, I have the
>>> following problem. Here is what I want to do, (with the wrong syntax):
>>>
>>> from numpy import *
>>>
>>> t=arange(0,20,.1)
>>> x=zeros(len(t),'f')
>>>
>>> idx=(t>5)                # <---this produces a Boolean array,
>>> probably not what you want.
>>> tau=5
>>> x[idx]=exp(-t[idx]/tau)  # <---this line is wrong (gives a TypeError)
>>>
>> What are you trying to do?  It is most unlikely that you need Boolean
>> values in x[idx]

[Apologies for piggybacking.]

Boolean arrays are perfectly valid indices and do exactly what the OP wants.

In [25]: t[idx]
Out[25]:
array([  5.1,   5.2,   5.3,   5.4,   5.5,   5.6,   5.7,   5.8,   5.9,
         6. ,   6.1,   6.2,   6.3,   6.4,   6.5,   6.6,   6.7,   6.8,
         6.9,   7. ,   7.1,   7.2,   7.3,   7.4,   7.5,   7.6,   7.7,
         7.8,   7.9,   8. ,   8.1,   8.2,   8.3,   8.4,   8.5,   8.6,
         8.7,   8.8,   8.9,   9. ,   9.1,   9.2,   9.3,   9.4,   9.5,
...

In [28]: (t[idx] == compress(idx, t)).all()
Out[28]: True

When used as indices, Boolean arrays are treated as arrays of Boolean values,
not 0s and 1s. Arrays of 0s and 1s used as indices would get the first and
second values of an array, respectively, as I think you were expecting.

In [35]: t[idx.astype(int)]
Out[35]:
array([ 0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
        0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
        0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
        0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
        0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0.1,  0.1,  0.1,  0.1,
        0.1,  0.1,  0.1,  0.1,  0.1,  0.1,  0.1,  0.1,  0.1,  0.1,  0.1,
 ...

-- 
Robert Kern
robert.kern at gmail.com

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter




More information about the Python-list mailing list