MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   在Matlab中排序 (https://www.labfans.com/bbs/showthread.php?t=23423)

poster 2019-12-10 20:41

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

例如,给出以下代码:

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

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

谢谢,

美茶



[B]回答:[/B]

我建议您分三步执行此操作:将“ 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)

[url=https://stackoverflow.com/questions/2827865]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 23:35

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.