我想对逗号分隔的列表中的元素进行排序。列表中的元素是结构体,我希望根据结构体中的一个字段对列表进行排序。
例如,给定以下代码:
L = {struct('obs', [1 2 3 4], 'n', 4), struct('obs', [6 7 5 3], 'n', 2)};我希望有一种方法可以根据字段'n‘对L进行排序。Matlab的排序函数仅适用于矩阵或数组以及字符串列表(甚至不适用于数字列表)。
对如何实现这一点有什么想法吗?
谢谢,
米卡
发布于 2010-05-13 23:13:08
我建议您分三步完成此操作:将'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)发布于 2010-05-14 00:19:17
这有点不切实际,但是如果单元数组L中的所有结构都有相同的字段(在本例中是obs和n ),那么将L存储为1 x N结构数组而不是1 x 1结构的1 x N单元数组会更有意义。
要将结构的1 x N单元数组转换为1 x N结构数组,可以执行以下操作:
L = [L{:}];或者,您可以使用对STRUCT的一次调用直接创建结构数组,而不是像在示例中那样创建结构的单元格数组:
L = struct('obs',{[1 2 3 4],[6 7 5 3]},'n',{4,2});现在solution from Jonas变得更简单了:
[junk,sortIndex] = sort([L.n]); %# Collect field n into an array and sort it
sortedL = L(sortIndex); %# Apply the sort to L发布于 2010-05-13 23:32:14
以下是Python中的解决方案:
L = [{'n': 4, 'obs': [1, 2, 3, 4]}, {'n': 2, 'obs': [6, 7, 5, 3]}]
L.sort(lambda a,b: a['n'].__cmp__(b['n']))
# L is now sorted as you wantedhttps://stackoverflow.com/questions/2827865
复制相似问题