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!