Sorting in Matlab
I would like to sort the items in a comma separated list. The items in the list are structures, and I would like the list to be sorted according to one of the fields in the structure.
For example, given the following code:
L = {struct('obs', [1 2 3 4], 'n', 4), struct('obs', [6 7 5 3], 'n', 2)};
I would like to have a way to sort L by field 'n'. Matlab's sort function only works on matrices or arrays and on lists of strings (not even on lists of numbers).
Any ideas on how this can be achieved?
Thanks,
Micah
a source to share
I suggest you do this in three steps: Extract 'n' into an array, sort the array, and therefore reorder the elements of the cell array.
%# get the n's
nList = cellfun(@(x)x.n,L);
%# sort the n and capture the reordering in sortIdx
[sortedN,sortIdx] = sort(nList);
%# use the sortIdx to sort L
sortedL = L(sortIdx)
a source to share
This is a bit of an aside, but if all the structures in the cell array L
have the same margins ( obs
and n
in this case) then it would make more sense to store it L
as a 1-by-1-by-1-by-1 array instead of a 1-by-1 cell array of 1-by-1 structures.
To convert a 1-by-cell array of cells to a 1-by-one structure array, you can do the following:
L = [L{:}];
Or, you can create an array of structures directly using a single STRUCT call instead of creating a cell array of structures as you did in your example:
L = struct('obs',{[1 2 3 4],[6 7 5 3]},'n',{4,2});
Now the solution from Jonas gets even easier:
[junk,sortIndex] = sort([L.n]); %# Collect field n into an array and sort it
sortedL = L(sortIndex); %# Apply the sort to L
a source to share