필터 지우기
필터 지우기

How to separate a column into rows based on the element of a different column?

조회 수: 2 (최근 30일)
Input: a = {1 2; 2 3; 3 5; -1 6; 5 7; 6 8; 7 9; 8 10; -1 11};
I have a 9x2 cell array matrix. I need my output this way: if the element in column 1 == -1, it will create a new row from the 1st element of column 2 to the element of column 2 until -1 in column 1 (inclusive). Then if -1 appears again in the first column, it will create a new row starting after the previous endpoint of column 2 to the element in column 2 until -1 appears in column 1 (inclusive).
Expected output: b = {2 3 5 6; 7 8 9 10 11}
I was trying b = a(cat(1,a{:,1}) >= -1 ,2:2).' but couldn't make separate rows. How can I do it?
  댓글 수: 2
Stephen23
Stephen23 2018년 10월 30일
편집: Stephen23 2018년 10월 30일
b = {2 3 5 6; 7 8 9 10 11}
This cell array is not possible because each row has a different number of elements.
Why are you storing numeric scalars in a cell array? This just makes processing the data pointlessly complex.
Md Shahidullah Kawsar
Md Shahidullah Kawsar 2018년 10월 30일
Thanks for your reply. Besides cell array, is it possible to deal with a different number of elements in each row?

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

채택된 답변

Stephen23
Stephen23 2018년 10월 30일
편집: Stephen23 2018년 10월 30일
This is a lot easier if you simply store the scalar numeric values in one numeric array (use cell2mat if required):
>> A = [1,2;2,3;3,5;-1,6;5,7;6,8;7,9;8,10;-1,11]
A =
1 2
2 3
3 5
-1 6
5 7
6 8
7 9
8 10
-1 11
Method one: diff and mat2cell:
>> X = diff([0;find(A(:,1)==-1)]);
>> C = mat2cell(A(:,2),X,1);
>> C{:}
ans =
2
3
5
6
ans =
7
8
9
10
11
Method two: cumsum and accumarray:
>> X = cumsum([true;A(1:end-1,1)==-1]);
>> C = accumarray(X,A(:,2),[],@(v){v});
>> C{:}
ans =
2
3
5
6
ans =
7
8
9
10
11

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by