Split a matrix in rows according to a vector

조회 수: 1 (최근 30일)
Eli Dim
Eli Dim 2015년 6월 28일
답변: Star Strider 2015년 6월 28일
Hello, If I have a matrix that looks like this:
A = [
[1, 0, 0, 5, 10, 5, 100, 300];
[1, 0, 0, 5, 10, 5, 100, 400];
[1, 0, 0, 5, 10, 5, 100, 450];
[1, 0, 0, 5, 10, 5, 100, 500];
[1, 0, 0, 5, 10, 5, 100, 550];
[1, 0, 0, 5, 10, 5, 100, 600];
[1, 0, 0, 5, 10, 5, 100, 700];
[1, 0, 0, 4, 10, 4, 100, 300];
[1, 0, 0, 5, 10, 5, 100, 450];
[1, 0, 0, 5, 10, 5, 100, 800];
];
and a vector that looks like this:
B = [ 1; 2; 1; 3; 2;1];
How can I split my matrix A according to this rule: The first sub-matrix A has a row number equal to the first value of B The second sub-matrix A has a row number equal to the second value of B etc. I would like to store the split sub-matrices in separate cells. So essentially, the first cell will look like this: 1, 0, 0, 5, 10, 5, 100, 300 the second cell will look like this:
1, 0, 0, 5, 10, 5, 100, 400
1, 0, 0, 5, 10, 5, 100, 450

채택된 답변

Star Strider
Star Strider 2015년 6월 28일
I would use mat2cell:
C = mat2cell(A, B, size(A,2));
C1 = C{1} % View Result
C2 = C{2} % View Result
C1 =
1 0 0 5 10 5 100 300
C2 =
1 0 0 5 10 5 100 400
1 0 0 5 10 5 100 450

추가 답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2015년 6월 28일
x=cumsum(B)-B+1
y=cumsum(B)
out=arrayfun(@(ii,jj) A(ii:jj,:),x,y,'un',0)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by