How do I split an array into small array of fixed size with increments by 1?

조회 수: 9 (최근 30일)
For example, I have an array, say
aa = [2 5 6 10 2 4 2 1 -1 -12 0 3 7];
What I want to do is create arrays of length 4, such as
[2 5 6 10], [5 6 10 2], [6 10 2 4], [10 2 4 2], [2 4 2 1], [4 2 1 -1], ....
and group them into a matrix. I understand this can be done in a for loop, but is there a way to vectorize this process?

채택된 답변

Bruno Luong
Bruno Luong 2022년 10월 28일
A=randi(10,1,10)
A = 1×10
3 10 1 4 8 8 9 3 10 6
k=4;
B = hankel(A(1:end-k+1),A(end-k+1:end))
B = 7×4
3 10 1 4 10 1 4 8 1 4 8 8 4 8 8 9 8 8 9 3 8 9 3 10 9 3 10 6
  댓글 수: 3
Alekhya Hati
Alekhya Hati 2022년 10월 28일
편집: Alekhya Hati 2022년 10월 28일
I found another method as well later on that worked for me
aa = [2 5 6 10 2 4 2 1 -1 -12 0 3 7];
bb = buffer(aa, 4, 3, 'nodelay')
bb = 4×10
2 5 6 10 2 4 2 1 -1 -12 5 6 10 2 4 2 1 -1 -12 0 6 10 2 4 2 1 -1 -12 0 3 10 2 4 2 1 -1 -12 0 3 7
Bruno Luong
Bruno Luong 2022년 10월 28일
I never use this command buffer, so I learn something.
It requires the signal processing toolbox though.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

DGM
DGM 2022년 10월 28일
편집: DGM 2022년 10월 28일
I'm sure there are other ways, but here's one way.
% the input
A = [2 5 6 10 2 4 2 1 -1 -12 0 3 7];
% the parameter
blocklen = 4;
% generate a 2D array of indices
nrows = numel(A)-blocklen+1;
idx = (1:blocklen) + (0:nrows-1).';
% build the output by direct addressing
B = A(idx)
B = 10×4
2 5 6 10 5 6 10 2 6 10 2 4 10 2 4 2 2 4 2 1 4 2 1 -1 2 1 -1 -12 1 -1 -12 0 -1 -12 0 3 -12 0 3 7

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by