Filter löschen
Filter löschen

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

1 Ansicht (letzte 30 Tage)
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 Kommentare
Stephen23
Stephen23 am 30 Okt. 2018
Bearbeitet: Stephen23 am 30 Okt. 2018
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 am 30 Okt. 2018
Thanks for your reply. Besides cell array, is it possible to deal with a different number of elements in each row?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 30 Okt. 2018
Bearbeitet: Stephen23 am 30 Okt. 2018
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

Weitere Antworten (0)

Kategorien

Mehr zu Cell Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by