查看单个帖子
旧 2019-12-10, 20:41   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 在Matlab中排序

我想对以逗号分隔的列表中的元素进行排序。列表中的元素是结构,我希望列表根据结构中的字段之一进行排序。

例如,给出以下代码:

L = {struct('obs', [1 2 3 4], 'n', 4), struct('obs', [6 7 5 3], 'n', 2)}; 我希望有一种方法可以按字段“ n”对L进行排序。 Matlab的sort函数仅适用于矩阵或数组以及字符串列表(甚至不包括数字列表)。

关于如何实现的任何想法?

谢谢,

美茶



回答:

我建议您分三步执行此操作:将“ n”提取到数组中,对数组进行排序,然后对单元格数组的元素重新排序。

%# get the n's nList = cellfun(@(x)xn,L); %# sort the n's and capture the reordering in sortIdx [sortedN,sortIdx] = sort(nList); %# use the sortIdx to sort L sortedL = L(sortIdx)

更多&回答...
poster 当前离线   回复时引用此帖