Sorting Cell Array Elements in Multiple Columns

4 次查看(过去 30 天)
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]

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2014-7-3
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,:)

更多回答(1 个)

Cedric
Cedric 2014-7-3
编辑:Cedric 2014-7-3
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]

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by