Is there a function like movsum which simply gets the values in a given sliding window rather than summing them?
1 view (last 30 days)
If I have a sequence
x = [1 2 3 4 5 6 7 8 9 10];
What is the most efficient way to get sub-vectors in a sliding window, i.e., if the window is of length 2;
I ask this because I need get these values at multiple different window lengths.
Thank you in advance.
Steven Lord on 4 Apr 2023
Let's use some starting data that's a little more varied than 1:10.
x = [1 2 3 4 5 6 7 8 9 10].^2
Define the window length.
windowLength = 2;
Where does each window start? There are windows starting with each element of x except for those that are too close to the end. "Too close" is less than windowLength-1 from the end; if we started at windowLength-2 from the end the window would extend past the end of the vector.
startingPoints = 1:numel(x)-(windowLength-1)
Now we define the window offsets from the starting point. The first point in the window is the starting point + 0, the next is the starting point + 1, etc. up through starting point + window length - 1.
windowOffsets = (1:windowLength)-1
Use implicit expansion to define the window indices by adding the starting points and the offsets, with different orientations.
windowIndices = windowOffsets + startingPoints.'
Get the corresponding elements from x.