I'm trying to optimize an algorithm that involves several vector multiplications where one vector stays the same and the other continually shifts until all calculations have been completed.
For example, if the static vector is
a = [3 2 0]
and the moving vector is
b = [2 5 6 3 8 4]
I would like to return
[[6 10 0], [15 12 0], [18 6 0], [9 16 0]] ([[2], [5], [6]] * [[3], [2], [0]] = [[6], [10], [0]] and [[5], [6], [3]] * [[3], [2], [0]] = [[15], [12], [0]], etc.). Is there an efficient way to do this calculation in python/numpy? Or will I just have to loop over slices of <b>b</b> and multiply each by <b>a</b>?
I've thought of putting a into a diagonal-like matrix:
[[3 2 0 0 0 0],
[0 3 2 0 0 0],
[0 0 3 2 0 0],
[0 0 0 3 2 0]]
and multiplying it by a diagonalized b like:
[[2 0 0 0 0 0],
[0 5 0 0 0 0],
[0 0 6 0 0 0],
[0 0 0 3 0 0],
[0 0 0 0 8 0],
[0 0 0 0 0 4]]
to get:
[[6 10 0 0 0 0],
[0 15 12 0 0 0],
[0 0 18 6 0 0],
[0 0 0 9 16 0]]
but this seems a little excessive and space-intensive.
Hope my question makes sense. Thanks for the help!
We can leverage np.lib.stride_tricks.as_strided
based scikit-image's view_as_windows
to get sliding windows. More info on use of as_strided
based view_as_windows
. So, with those strided-view
, assuming arrays as inputs, it would be -
In [7]: from skimage.util.shape import view_as_windows
In [8]: view_as_windows(b,len(a))*a
Out[8]:
array([[ 6, 10, 0],
[15, 12, 0],
[18, 6, 0],
[ 9, 16, 0]])