Azzera filtri
Azzera filtri

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

2 visualizzazioni (ultimi 30 giorni)
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 Commenti
Stephen23
Stephen23 il 30 Ott 2018
Modificato: Stephen23 il 30 Ott 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 il 30 Ott 2018
Thanks for your reply. Besides cell array, is it possible to deal with a different number of elements in each row?

Accedi per commentare.

Risposta accettata

Stephen23
Stephen23 il 30 Ott 2018
Modificato: Stephen23 il 30 Ott 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

Più risposte (0)

Categorie

Scopri di più su Multidimensional Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by