Sort struct fields by their length

1 回表示 (過去 30 日間)
Fabio Pulcini
Fabio Pulcini 2019 年 3 月 20 日
回答済み: Alex Mcaulley 2019 年 3 月 20 日
Hi everyone,
i have a struct of N fields in random order, each one is composed by an array Nx1. What i need to do is to sort the order of fields by their lengths, so that the first field would be the longest one and the last filed would be the shortest one.
Can anyone help me?
Thanks!

回答 (3 件)

KSSV
KSSV 2019 年 3 月 20 日
% MAke structure for demo
S = struct ;
for i = 1:10
S(i).val = rand(randsample(100,1),1) ;
end
%% Gt lengths of each structure fields
L = zeros(length(S),1) ;
for i = 1:length(S)
L(i) = length(S(i).val) ;
end
% sort into order
[L,idx] = sort(L) ;
S = S(idx) ; % arrange
  1 件のコメント
Luna
Luna 2019 年 3 月 20 日
編集済み: Luna 2019 年 3 月 20 日
This is 1xN struct array with one field (val). S(idx) might not work if he has a 1x1 struct with N fields.

サインインしてコメントする。


Luna
Luna 2019 年 3 月 20 日
Hi,
Try this:
% Create myStruct with Alphabet Fields and add random 1XN array to the
% fields
fieldList = cellstr(('a':'z')')';
for i = 1:numel(fieldList)
myStruct.(fieldList{i}) = rand(1,randi(30));
end
%% Sorting starts here
myCell = struct2cell(myStruct); % convert to cell array
lenghtofFields = cellfun(@length,myCell,'UniformOutput',false); % get the lengths
[vals,orders] = sort(cell2mat(lenghtofFields),'descend'); % get the orders from sorted lenght
structFieldNames = fieldnames(myStruct); %get your struct's fieldnames (I could use fieldList but you can avoid above creation section)
NewStructwithOrderedFields = orderfields(myStruct,structFieldNames(orders)); % order fields according to orders array

Alex Mcaulley
Alex Mcaulley 2019 年 3 月 20 日
Another option:
a.one = rand(1,10);
a.two = rand(1,15);
a.three = rand(1,8);
a.four = rand(1,12);
[~,idx] = sort(structfun(@numel,a),'descend')
a = orderfields(a, idx);

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by