Extract consecutive elements from a vector in a sliding manner

2 ビュー (過去 30 日間)
LH
LH 2025 年 4 月 30 日
回答済み: Walter Roberson 2025 年 4 月 30 日
Hi all,
If I have a vector:
A = [1 ;2 ;3 ;4 ;5 ;6];
and I want to extract 2 elements in a way that I should get in each loop:
for i 1:size(A,1)
A_slice = [?];
end
The answer I'm looking for, for each loop I should get:
%Loop 1: A_slice=[1;2]
%Loop 2: A_slice=[3;4]
%Loop 3: A_slice=[5;6]
any help would be appreicted.

採用された回答

Matt J
Matt J 2025 年 4 月 30 日
A = [1 ;2 ;3 ;4 ;5 ;6];
Ar=reshape(A,2,[]);
for i=1:size(Ar,2)
A_slice=Ar(:,i)
end
A_slice = 2×1
1 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
A_slice = 2×1
3 4
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
A_slice = 2×1
5 6
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

その他の回答 (2 件)

dpb
dpb 2025 年 4 月 30 日
編集済み: dpb 2025 年 4 月 30 日
Alternatively, depending upon end use, without the explicit loop can generate the subsets directly...
x=[1:6].';
n=2;
slice=arrayfun(@(i)x(i:i+n-1),1:n:numel(x)-1,'UniformOutput',false)
slice = 1x3 cell array
{2x1 double} {2x1 double} {2x1 double}
or, more succinctly
slice=num2cell(reshape(x,n,[]),1)
slice = 1x3 cell array
{2x1 double} {2x1 double} {2x1 double}
ADDENDUM: I see now that the latter above was already shown by @Matt J, I just recast into the cell array with generic number of elements. Of course, either fails if numel(x) isn't integer multiple of n.

Walter Roberson
Walter Roberson 2025 年 4 月 30 日
A = [1 ;2 ;3 ;4 ;5 ;6];
A_slice = buffer(A, 2)
A_slice = 2×3
1 3 5 2 4 6
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
now do things with the columns.
buffer() requires the Signal Processing Toolbox. (Personally, I think it ought to be made part of basic MATLAB.)
buffer() has the advantage of smoothly handling the case where the input vector is not an exact multiple of the buffer size.

カテゴリ

Help Center および File ExchangeImage Data Workflows についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by