calculating on matrix indices

Travis E. Oliphant oliphant.travis at ieee.org
Thu Feb 16 20:54:27 EST 2006


Brian Blais wrote:
> Hello,
> 
> 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)
> tau=5
> x[idx]=exp(-t[idx]/tau)  # <---this line is wrong (gives a TypeError)

Hi Brian,

Just to let you know, you are more likely to get good answers by mailing 
numpy-discussions at lists.sourceforge.net then posting to this list.

The indexing technique you are using is actually fine.  The trouble you 
are having is that t is a double-precision array (and thus so is 
exp(-t[idx]/tau)  while x is a single-precision array.

Compare:

x.dtype.name
t.dtype.name

Because you are trying to store something with greater precision into an 
array with less precision you get a TypeError.

So, either change x to be double precision:

x = zeros(len(t), float)

#the default Python float is doubleprecision

or change t to be single precision:

t = arange(0,20,.1,dtype=single)

Good luck,

-Travis




More information about the Python-list mailing list