Vectorization
Paul McGuire
ptmcg at austin.rr._bogus_.com
Tue Jun 6 09:43:24 EDT 2006
"RonnyM" <ronnyma at math.uio.no> wrote in message
news:1149595753.611358.189070 at i39g2000cwa.googlegroups.com...
> Hi!
>
> Need to vectorize this, but do not have a clue.
>
> a = n*m matrix
> x and y are n and m vectors
>
> Suggestions?
>
>
>
> def fill(a, x, y):
> for i in range(1,a.shape[0]):
> xp = x[i]
> for j in range(a.shape[1]):
> yp = y[j]
> a[i,j] = sin(xp*yp)*exp(-xp*yp) + a[i-1,j]
> return a
>
> Thanks in advance,
>
> Ronny Mandal
>
Something like this, but the first row in a is never modified, is this
correct?
Note: this is a brute force Python attempt at a matrix, using a list of
lists. Look also at the array and numarray modules.
-- Paul
from math import sin,exp
def fill(a,x,y):
aRowCount = len(x)
aColCount = len(y)
#a = [[0]*aColCount for i in range(aRowCount)]
for ii,xp in enumerate(x[1:]):
i = ii+1
for j,yp in enumerate(y):
a[i][j] = sin(xp*yp)*exp(-xp*yp) + a[i-1][j]
return a
or more tersely (note - no side-effect of modifying a in place, makes a new
copy):
def fill2(a,x,y):
fn = lambda t,u,v:sin(t*u)*exp(-t*u) + v
return [a[0]] + [ [ fn(xp,yp,aa) for (yp,aa) in zip(y,arow) ] for
(xp,arow) in zip(x[1:],a[:-1]) ]
More information about the Python-list
mailing list