matlab - 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)?
我必须从上述数据类型(结构和元胞数组)开始,但是,如果这有帮助,我愿意将它们转换为任何其他格式。
解决方案
我不得不承认现在的答案很简单:
[~, 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)
推荐阅读
- c# - 为什么我的单元测试因 switch 语句而失败?
- excel - PowerQuery - 并排导入文件
- objective-c - 如何运行一个shell脚本?
- html - 如何在边框上添加元素并使其在调整窗口大小时保持位置?
- r - 按组检查因子变化
- c# - 如何将 FTP 文件发送到客户端浏览器?
- ios - 为什么使用 iOS URL Schema 打开应用程序时,Google 地图无法解析路线?
- spring - 禁用或覆盖 Spring 关联资源
- css - Vuetify 在 v-slot:label 上添加样式
- javascript - 通过将脚本集成到 apppresser 中,admob 免费插页式广告仅向我显示测试广告而非真实广告