Sort fields of struct by length and alphabetically
    26 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    Michel C
 el 20 de Mayo de 2021
  
    
    
    
    
    Comentada: KAE
      
 el 20 de Ag. de 2021
            I've been trying to sort the fields of a struct by combination of length and name. Length should take precedence, but if the length of two or more fields is equal (for example if they are scalar), those should be sorted alphabetically (within that group), where names starting with capital letter should take precedence. I'm coming up with nothing that works. Anybody?
Best regards MC
Respuesta aceptada
  Stephen23
      
      
 el 20 de Mayo de 2021
        
      Editada: Stephen23
      
      
 el 20 de Mayo de 2021
  
      S.aa = rand(3,1);
S.bb = 1;
S.cc = rand(8,2);
S.dd = 1;
S.Ee = 1;
S.Ff = rand(3,1)
Method one: sort and indexing:
N = structfun(@numel,S);
F = fieldnames(S);
[~,X] = sort(F);
[~,Y] = sort(N(X),'descend');
Z = orderfields(S,F(X(Y)))
Method two: table and sortrows:
[~,X] = sortrows(table(N,F),[-1,2]);
Z = orderfields(S,F(X))
Más respuestas (0)
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!


