poster
2019-12-10, 20:41
我想对以逗号分隔的列表中的元素进行排序。列表中的元素是结构,我希望列表根据结构中的字段之一进行排序。
例如,给出以下代码:
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)
更多&回答... (https://stackoverflow.com/questions/2827865)
例如,给出以下代码:
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)
更多&回答... (https://stackoverflow.com/questions/2827865)