Elis
Elis

Reputation: 54

Sliding dot product

I have two 1D arrays

x = np.random.rand(100)
alpha = np.array([2, 3, 4])

I will refer to the elements of x as x_0, x_1, etc.

How, in the fastest way possible, can I create a sort of 'sliding dot product' from this, more specifically the following 1D array:

array([2*x_0 + 3*x_1 + 4*x_2,
2*x_1 + 3*x_2 + 4*x_3,
2*x_2 + 3*x_3 + 4*x_4,
...,
2*x_98 + 3*x_99 + 4*x_100])

I can't think of a way that doesn't use for loops. I'm sure there's a more elegant way.

Upvotes: 0

Views: 96

Answers (1)

Ahmed AEK
Ahmed AEK

Reputation: 17616

that's called convolution, in your case you want to use it in "valid" mode so that it doesn't pad with zeros.

import numpy as np
x = np.random.rand(100)
alpha = np.array([2, 3, 4])

res = np.convolve(x,alpha,mode="valid")
print(len(res))  # 98, you can count it yourself on a paper.

Upvotes: 1

Related Questions