Spliting a cell based on the values of a column

2 visualizzazioni (ultimi 30 giorni)
Hi I have a NX2 cell, where the the first column has a data type of the kind int64 and the 2nd column contains strings.
I want to split this cell into smaller cells based on the value of integer in the 1st column. That is if my cell variable is: cell=[1 PB1;3 PB2;1 PBC;2 PB1;1 PBC.......],
I want to create smaller cells out of it; i.e cell_1 which contains all the rows of the original cell which has 1 in their 1st column, cell_2 with 2 in the 1st column and so on . Can this be done without using a for loop, as N can be quite large for me in some cases.
I did it for matrices using logical indexing, but my matrices had only either 1 or2 or 3 or 4 in the 1st column and there I had to specify the value of the elements for carrying out splitting.
Now for the cell array I have values running from 1 upto 290 or more. So,can this be done for cell arrays without exactly specifying what is the value of the element in the column-1 of the cell.
Thanks, Dibakar

Risposta accettata

goerk
goerk il 3 Giu 2016
Take the data from column 1 and perform the command
sortInd = unique(column1data);
now you can loop over this values (sortInd) and perform the same as for your matrix solution.

Più risposte (1)

Stephen23
Stephen23 il 3 Giu 2016
Modificato: Stephen23 il 3 Giu 2016
There is no need to use any loop:
>> C = {1,'PB1';3,'PB2';1,'PBC';2,'PB1';1,'PBC'}
>> [V,idx] = sort([C{:,1}])
>> D = diff([find([1,diff(V)]),1+numel(V)])
>> out = mat2cell(C(idx,:),D,2)
>> out{:}
ans =
[1] 'PB1'
[1] 'PBC'
[1] 'PBC'
ans =
[2] 'PB1'
ans =
[3] 'PB2'

Community Treasure Hunt

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

Start Hunting!

Translated by