Is there a function like movsum which simply gets the values in a given sliding window rather than summing them?

3 次查看(过去 30 天)
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;
[1 2]
[2 3]
[3 4]
[4 6]
etc.
I ask this because I need get these values at multiple different window lengths.
Thank you in advance.

采纳的回答

Steven Lord
Steven Lord 2023-4-4
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
x = 1×10
1 4 9 16 25 36 49 64 81 100
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)
startingPoints = 1×9
1 2 3 4 5 6 7 8 9
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
windowOffsets = 1×2
0 1
Use implicit expansion to define the window indices by adding the starting points and the offsets, with different orientations.
windowIndices = windowOffsets + startingPoints.'
windowIndices = 9×2
1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10
Get the corresponding elements from x.
x(windowIndices)
ans = 9×2
1 4 4 9 9 16 16 25 25 36 36 49 49 64 64 81 81 100

更多回答(2 个)

David Hill
David Hill 2023-4-4
b=1:10;
a=b;
n=5;%window size
for k=1:n-1
a=[a;circshift(b,-k)];
end
a=a';
a=a(1:length(b)-n+1,:)
a = 6×5
1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9 6 7 8 9 10

Bora Eryilmaz
Bora Eryilmaz 2023-4-4
编辑:Bora Eryilmaz 2023-4-4
If you have access to the Predictive Maintenance Toolbox, you can use the phaseSpaceReconstruction command:
x = [1 2 3 4 5 6 7 8 9 10];
sz = 2;
y = phaseSpaceReconstruction(x, 1, sz)
y = 9×2
1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10
sz = 4;
y = phaseSpaceReconstruction(x, 1, sz)
y = 7×4
1 2 3 4 2 3 4 5 3 4 5 6 4 5 6 7 5 6 7 8 6 7 8 9 7 8 9 10

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by