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

1 次查看(过去 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
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 中查找有关 Cell Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by