MATLAB: How to sort an array of structures based upon a particular field in MATLAB

MATLABstruct

I have a structure array, and I would like to use a function like SORT to arrange those structures.

Best Answer

The ability to use SORT with a structure array is not available in MATLAB.
As a workaround you can modify the following code that sorts an array of structures based upon a numeric first field:
%%Create dummy struct array
a.n=1;
a.name='a';
b.n=3;
b.name='b';
c.n=2;
c.name='c';
array = [a b c];
%%Sort the array
cells = struct2cell(array); %converts struct to cell matrix
sortvals = cells(1,1,:); % gets the values of just the first field
mat = cell2mat(sortvals); % converts values to a matrix
mat = squeeze(mat); %removes the empty dimensions for a single vector
[sorted,ix] = sort(mat); %sorts the vector of values
array = array(ix); %rearranges the original array