How can I sort an array of structures based upon a particular field in MATLAB?
14 次查看(过去 30 天)
显示 更早的评论
I have a structure array, and I would like to use a function like SORT to arrange those structures.
采纳的回答
MathWorks Support Team
2009-6-27
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
0 个评论
更多回答(1 个)
Observer
2017-1-18
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) ;
else
disp ('Array of struct is empty');
end
end
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!