Sort a variables in structure

조회 수: 4 (최근 30일)
Gabriele Curcio
Gabriele Curcio 2022년 5월 5일
편집: Stephen23 2022년 5월 6일
I have this kind of variables in a struct:
var_1
var_10
var_11
...
var_19
var_2
var_21
and so on until var_24
Is there a manner to sort them like
var_1
var_2
var_3
var_4
...
var_24
?

채택된 답변

Davide Masiello
Davide Masiello 2022년 5월 5일
편집: Davide Masiello 2022년 5월 5일
See example below
clear,clc
s.var_1 = 1;
s.var_6 = 1;
s.var_3 = 1;
s.var_2 = 1;
s.var_5 = 1;
s.var_4 = 1;
s
s = struct with fields:
var_1: 1 var_6: 1 var_3: 1 var_2: 1 var_5: 1 var_4: 1
orderfields(s)
ans = struct with fields:
var_1: 1 var_2: 1 var_3: 1 var_4: 1 var_5: 1 var_6: 1

추가 답변 (1개)

Stephen23
Stephen23 2022년 5월 5일
편집: Stephen23 2022년 5월 6일
Rather than forcing pseudo-indices into fieldnames, why not use an array with indexing (e.g. a cell array) ?
Here are two ways to sort those fieldnames into alphanumeric order:
S0.var_1 = 101;
S0.var_10 = 110;
S0.var_11 = 111;
S0.var_19 = 119;
S0.var_2 = 102;
S0.var_21 = 121
S0 = struct with fields:
var_1: 101 var_10: 110 var_11: 111 var_19: 119 var_2: 102 var_21: 121
Method 1: REGEXP and SORT (only sorts the numeric part):
[~,X] = sort(str2double(regexp(fieldnames(S0),'\d+$','match','once')));
S1 = orderfields(S0,X)
S1 = struct with fields:
var_1: 101 var_2: 102 var_10: 110 var_11: 111 var_19: 119 var_21: 121
Method two: NATSORT (must be downloaded first, provides a full alphanumeric sort):
[~,X] = natsort(fieldnames(S0));
S2 = orderfields(S0,X)
S2 = struct with fields:
var_1: 101 var_2: 102 var_10: 110 var_11: 111 var_19: 119 var_21: 121

카테고리

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

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by