Sorting Cell Array Elements in Multiple Columns

1 view (last 30 days)
Suppose I have a cell variable A{1} with contents as follow:
A{1}=
1 100 0 [6,7,8,9,10,11,12]
2 110 0 [6,7,8,9,10,11,12]
25 35 [5,14] [6,7,8,9,10,11,12]
35 38 4 <1x12 double>
36 37 4 <1x12 double>
37 36 4 <1x12 double>
May I know how can I sort the elements inside the cell array based on these criteria: First, Length of elements in Column 3 (Ignoring zero) in ascending order. Then, the values in Column 2 in descending order.
The resultant should be something similar to this:
resultant{1}=
35 38 4 <1x12 double>
36 37 4 <1x12 double>
37 36 4 <1x12 double>
25 35 [5,14] [6,7,8,9,10,11,12]
2 110 0 [6,7,8,9,10,11,12]
1 100 0 [6,7,8,9,10,11,12]

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 3 Jul 2014
A={1 100 0 [6,7,8,9,10,11,12]
2 110 0 [6,7,8,9,10,11,12]
25 35 [5,14] [6,7,8,9,10,11,12]
35 38 4 [6,7,8,9,10,11,12]
36 37 4 [6,7,8,9,10,11,12]
37 36 4 [6,7,8,9,10,11,12]}
c31=cellfun(@(x) any(x),A(:,3))
c32=cellfun(@(x) length(x),A(:,3))
idx3=c31.*c32
idx3(idx3==0)=inf;
[~,ii]=sortrows([cell2mat(A(:,2)) idx3],[2 -1])
out=A(ii,:)

More Answers (1)

Cedric
Cedric on 3 Jul 2014
Edited: Cedric on 3 Jul 2014
Here is one way to do it
B = cellfun( @length, A{1}(:,3) ) ; % Get length of el. of 3rd col of A{1}.
B([A{1}{:,3}] == 0) = Inf ; % Set length = Inf where 0.
B = [[A{1}{:,2}].', B] ; % Append col 2.
[~,ix] = sortrows( B, [2,-1] ) ; % Sort col 2 asc first, then col 1 desc.
resultant{1} = A{1}(ix,:) ; % Re-index A{1}.
Running this, you get
>> resultant{1}
ans =
[35] [ 38] [ 4] <1x12 double>
[36] [ 37] [ 4] <1x12 double>
[37] [ 36] [ 4] <1x12 double>
[25] [ 35] [1x2 double] [1x7 double]
[ 2] [110] [ 0] [1x7 double]
[ 1] [100] [ 0] [1x7 double]

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!