Sort struct fields by their length
1 回表示 (過去 30 日間)
古いコメントを表示
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!
0 件のコメント
回答 (3 件)
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
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
0 件のコメント
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);
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Structures についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!