MATLAB Answers

How can I sort an array of structures based upon a particular field in MATLAB?

187 views (last 30 days)
I have a structure array, and I would like to use a function like SORT to arrange those structures.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
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
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

More Answers (3)

Observer on 18 Jan 2017
function outStructArray = SortArrayofStruct( structArray, fieldName )
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
if ( ~isempty(structArray) && length (structArray) > 0)
[~,I] = sort(arrayfun (@(x) x.(fieldName), structArray)) ;
outStructArray = structArray(I) ;
disp ('Array of struct is empty');

Meer Jani
Meer Jani on 12 May 2019
% Sort by Column
function SortedMatrix = SortMatrixOfStructs(Matrix, Columns)
for i = 1: Columns
cells = struct2cell(Matrix(:,i));
sortvals = cells(1,:,1); % Gets the values of just the first field by column
mat = cell2mat(sortvals);
mat = squeeze(mat);
[sorted,ix] = sort(mat);
Matrix(:,i) = Matrix(ix,i);
SortedMatrix = Matrix;
% Sort by Rows
function SortedMatrix = SortMatrixOfStructs(Matrix, Rows)
for i = 1: Rows
cells = struct2cell(Matrix(i,:));
sortvals = cells(1,1,:); % Gets the values of just the first field by Row
mat = cell2mat(sortvals);
mat = squeeze(mat);
[sorted,ix] = sort(mat);
Matrix(i,:) = Matrix(i,ix);
SortedMatrix = Matrix;

He Zhu Zhu
He Zhu Zhu on 11 Jul 2021 at 8:41
function result = sortby(structArray, fieldName, reverse)
% sort a structure array by a field
if nargin < 3, reverse = false; end
[~, idx] = sort({structArray.(fieldName)});
if reverse
idx = flip(idx);
result = structArray(idx);



Community Treasure Hunt

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

Start Hunting!