[Numpy-discussion] Familiar w/ reduce ?

Sven Schreiber svetosch at gmx.net
Tue Jun 26 04:52:24 EDT 2007


Pierre GM schrieb:
> All,
> I have a (m_1+1,m_2+1) matrix of 0 and 1, and I need to compute a second 
> matrix U by recurrence.
> A double-loop as such
> #............................
> U = empty((m_1+1, m_2+1))
> U[:,0] = C[:,0]
> U[0,:] = C[0,:]
> for i in range(1,m_1+1):
>     for j in range(1,m_2+1):
>         U[i,j] = C[i,j] * (U[i,j-1] + U[i-1,j])
> #............................
> does the trick, but I suspect there is not a simpler, more elegant solution. 
> Would anybody have any idea ?
> Thanks a lot in advance, and all my apologies for being a tad lazy...
> 

Going from two to one loop at least seems relatively easy; what about
something like (untested, especially all the parentheses...):

for i in range (1,m_1+1):
    U[i,1:] = dot(C[i,1:], vstack((U[i,:-1],U[i-1,1:])).sum(axis=0))

Actually, now that I see the structure more clearly, what about

tempU1 = U[:-1,1:] # upper right block (w/o last row and first col)
tempU2 = U[1:,:-1] # lower left (w/9 first row and last col)
U[1:,1:] = dot(C[1:,1:], tempU1+tempU2) # hopefully does it elementwise?

> (PS: FYI, it's for a reimplementation of the Kolmogorov-Smirnov test 
> statistic, where ties occur)

Glad that there are other applied statisticians (maybe even
econometrician?) around working with plain old 2d matrices... Would you
mind posting the resulting code?

cheers,
sven




More information about the NumPy-Discussion mailing list