Sorting Cell Array Elements in Multiple Columns
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
RDG
el 3 de Jul. de 2014
Comentada: RDG
el 3 de Jul. de 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]
0 comentarios
Respuesta aceptada
Azzi Abdelmalek
el 3 de Jul. de 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,:)
Más respuestas (1)
Cedric
el 3 de Jul. de 2014
Editada: Cedric
el 3 de Jul. de 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]
Ver también
Categorías
Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!