Sort struct fields by their length

6 Ansichten (letzte 30 Tage)
Fabio Pulcini
Fabio Pulcini am 20 Mär. 2019
Beantwortet: Alex Mcaulley am 20 Mär. 2019
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!

Antworten (3)

KSSV
KSSV am 20 Mär. 2019
% 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 Kommentar
Luna
Luna am 20 Mär. 2019
Bearbeitet: Luna am 20 Mär. 2019
This is 1xN struct array with one field (val). S(idx) might not work if he has a 1x1 struct with N fields.

Melden Sie sich an, um zu kommentieren.


Luna
Luna am 20 Mär. 2019
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 am 20 Mär. 2019
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);

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by