smi*_*hak 2 sorting matlab list
我想在逗号分隔列表中对元素进行排序.列表中的元素是结构体,我希望列表根据结构中的一个字段进行排序.
例如,给出以下代码:
L = {struct('obs', [1 2 3 4], 'n', 4), struct('obs', [6 7 5 3], 'n', 2)};
Run Code Online (Sandbox Code Playgroud)
我希望有一种方法可以通过字段'n'对L进行排序.Matlab的sort函数仅适用于矩阵或数组以及字符串列表(甚至不是数字列表).
关于如何实现这一点的任何想法?
谢谢,
米莎
我建议你分三步完成:将'n'提取到数组中,对数组进行排序,然后重新排序单元格数组的元素.
%# get the n's
nList = cellfun(@(x)x.n,L);
%# sort the n's and capture the reordering in sortIdx
[sortedN,sortIdx] = sort(nList);
%# use the sortIdx to sort L
sortedL = L(sortIdx)
Run Code Online (Sandbox Code Playgroud)