首页 > 解决方案 > Matlab:如何使用另一个向量按其中一个列对结构进行排序

问题描述

如何以其中一个列等于某个向量的方式对结构进行排序?下面是一个例子,它说明了我的意思。

我有以下结构和向量:

% What I have:
my_struct = struct('value1', {4, 2, 1}, 'letters', {'CD', 'AB', 'XY'}, 'value2', {5, 3, 1});
% Looks like:
% 4   'CD'    5
% 2   'AB'    3
% 1   'XY'    1

my_cell_array = {'CD', 'XY', 'AB'};
% Looks like:
% 'CD' 'XY' 'AB'

现在我尝试以第二列与以下顺序相同的方式对结构进行排序my_cell_array

% What I try:
[~, my_order_struct] = sort({my_struct(:).letters});
% Gives:
% 2 1 3

my_struct_ordered_alphabetically = my_struct(my_order_struct);
% Gives:
% 2   'AB'    3
% 4   'CD'    5
% 1   'XY'    1

my_struct_ordered = my_struct_ordered_alphabetically(my_order_cell);
% Should give:
% 4   'CD'    5
% 1   'XY'    1
% 2   'AB'    3

但是,我需要找到my_order_cell我的代码的最后一行。排序在这里并不能完全做到这一点:

[~, my_order_cell] = sort(my_cell_array);
% Gives me: 3 1 2 (vector that can be used to sort the cell array alphabetically)
% What I need: 2 3 1 (vector with the alphabetical order of the cell array elements)

因此,我此时的确切问题是:如何提取单元格数组的字母顺序(2 3 1 而不是 3 1 2)?

我必须从上述数据类型(结构和元胞数组)开始,但是,如果这有帮助,我愿意将它们转换为任何其他格式。

标签: matlabsortingstructcellcell-array

解决方案


我不得不承认现在的答案很简单:

[~, my_order_cell] = sort(my_cell_array);
% Gives me: 3 1 2 (vector that can be used to sort the cell array alphabetically)

[~, my_order_cell2] = sort(my_order_cell);
% Gives me: 2 3 1 (vector with the alphabetical order of the cell array elements)

推荐阅读