简体   繁体   中英

Matlab: How to sort a struct by one of its columns using another vector

How can I order a struct in a way that one of its columns are equal to a certain vector? Below is an example which shows what I mean.

I have the following struct and vector:

% 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'

Now I try to sort the struct in a way that the second column is in the same order as 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

However, I need to find my_order_cell for the last row of my code. Sort does not exactly do the trick here:

[~, 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)

My exact question at this point is therefore: How do I extract the alphabetical order of a cell array (the 2 3 1 instead of the 3 1 2)?

I have to start with the above data types (struct and cell array), however, I would be willing to convert them to any other format if this would help.

I have to admit the answer is quite trivial now:

[~, 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM