calculating on matrix indices

Paul Probert pprobert at wisc.edu
Thu Feb 16 22:58:36 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)
> 
> #------------------
> 
> what is the best way to replace the wrong line with something that works: replace all 
> of the values of x at the indices idx with exp(-t/tau) for values of t at indices idx?
> 
> I do this all the time in matlab scripts, but I don't know that the pythonic 
> preferred method is.
> 
Brian,
First, let me warn you I only know the old Numeric, and I haven't made 
the jump to Numpy yet. I'm told the syntax is about the same though.
Using nonzero, put, and take, I can do what you want like this:

import Numeric as num
t=num.arange(0,20,.1)
x=num.zeros(len(t),'f')
idx=num.nonzero(t>5)
tau=5.
num.put(x,idx,num.exp(-num.take(t,idx)/tau))

Kinda messy compared to Matlab. Do you know about Octave 
(www.octave.org)? It tries to be compatible with Matlab syntax. Of 
course it lacks the other niceties of python.

Paul Probert





More information about the Python-list mailing list