Sorting Cell Array Elements in Multiple Columns

조회 수: 5 (최근 30일)
RDG
RDG 2014년 7월 3일
댓글: RDG 2014년 7월 3일
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