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!

回答(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 CenterFile Exchange 中查找有关 Structures 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by