Alexander McFarlane
Alexander McFarlane

Reputation: 11293

apply along axis using arrays as indicies

I am trying to do this function in-place without a loop:

for i in xrange(2):
    trend[i] = np.convolve(dat[i,0], aW3[:,i], 'same').sum()

My best attempt is as follows:

trend[:2] = np.apply_along_axis(
    func1d=lambda x: np.convolve(x, aW3[:,i], 'same').sum(),
    axis=1,
    arr=dat[:2,0])

but I can't figure out how to correctly index aW3[:,i] through func1d

Constants Used

aW3 = np.array( [[ 0.259,  0.407],
                 [ 0.37 ,  0.407],
                 [ 0.259,  0.185],
                 [ 0.111,  0.   ]])
dat = np.array([0.02360784,  0.0227628 ,  0.0386366 ,  0.03338596,  0.03141621, 0.03430469])
dat = dat.reshape(dat.shape[0], 1) # in columns

Upvotes: 0

Views: 406

Answers (2)

Divakar
Divakar

Reputation: 221584

It seems you can just use np.einsum for a vectorized solution, like so -

trend = np.einsum('i,ji->i',dat[0:aW3.shape[1],0],aW3)

Or with broadcasting -

trend = (dat[0:aW3.shape[1],0]*aW3).sum(0)

Upvotes: 1

dlask
dlask

Reputation: 8982

trend = np.fromiter((np.convolve(dat[i,0], aW3[:,i], 'same').sum() for i in xrange(2)), float)

Upvotes: 1

Related Questions