Sort fields of struct by length and alphabetically

조회 수: 7 (최근 30일)
Michel C
Michel C 2021년 5월 20일
댓글: KAE 2021년 8월 20일
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

채택된 답변

Stephen23
Stephen23 2021년 5월 20일
편집: Stephen23 2021년 5월 20일
S.aa = rand(3,1);
S.bb = 1;
S.cc = rand(8,2);
S.dd = 1;
S.Ee = 1;
S.Ff = rand(3,1)
S = struct with fields:
aa: [3×1 double] bb: 1 cc: [8×2 double] dd: 1 Ee: 1 Ff: [3×1 double]
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)))
Z = struct with fields:
cc: [8×2 double] Ff: [3×1 double] aa: [3×1 double] Ee: 1 bb: 1 dd: 1
Method two: table and sortrows:
[~,X] = sortrows(table(N,F),[-1,2]);
Z = orderfields(S,F(X))
Z = struct with fields:
cc: [8×2 double] Ff: [3×1 double] aa: [3×1 double] Ee: 1 bb: 1 dd: 1

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by