フィルターのクリア

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
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 Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by