How to extract matrix with different starting index for each row?

조회 수: 4 (최근 30일)
Katherine Liu
Katherine Liu 2020년 10월 20일
댓글: Katherine Liu 2020년 10월 20일
I am not sure how to extract from a matrix a smaller matrix with different starting index for each row.
For example,
Original matrix (4x5):
[1 2 3 4 5]
[6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]
Desired output (4,3):
[2 3 4]
[6 7 8]
[13 14 15]
[17 18 19]
where the starting index for each row is [2,1,3,2]
Thank you!

채택된 답변

Fangjun Jiang
Fangjun Jiang 2020년 10월 20일
%%
Orig=transpose(reshape(1:20,5,[]))
StartPos=[2;1;3;2];
Wid=3;
row=repmat((1:size(Orig,1))',1,Wid);
col=StartPos+(0:Wid-1);
index=sub2ind(size(Orig),row,col);
out=Orig(index)

추가 답변 (0개)

카테고리

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