Effacer les filtres
Effacer les filtres

Sorting Cell Array Elements in Multiple Columns

4 vues (au cours des 30 derniers jours)
RDG
RDG le 3 Juil 2014
Commenté : RDG le 3 Juil 2014
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]

Réponse acceptée

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

Plus de réponses (1)

Cedric
Cedric le 3 Juil 2014
Modifié(e) : Cedric le 3 Juil 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]
  1 commentaire
RDG
RDG le 3 Juil 2014
Thank you Cedric for your explanation.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by