Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
|
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
我想对以逗号分隔的列表中的元素进行排序。列表中的元素是结构,我希望列表根据结构中的字段之一进行排序。
例如,给出以下代码: 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) 更多&回答... |
![]() |
![]() |