Ordering vectors of numbers of type double and strings according to another vector

1 回表示 (過去 30 日間)
L'O.G.
L'O.G. 2022 年 12 月 7 日
回答済み: Eric Delgado 2022 年 12 月 7 日
How do I order the following arrays?
vector_1 = [1 3 7 8 9 10];
string_1 = {'apples' 'pears' 'plums' 'oranges' 'peaches' 'grapes'};
Specifically, I want to re-order them according to [3 1 7 9 8 10] for vector_1.

採用された回答

Voss
Voss 2022 年 12 月 7 日
vector_1 = [1 3 7 8 9 10];
string_1 = {'apples' 'pears' 'plums' 'oranges' 'peaches' 'grapes'};
vector_1_reordered = [3 1 7 9 8 10];
[~,idx] = ismember(vector_1_reordered,vector_1);
string_1_reordered = string_1(idx)
string_1_reordered = 1×6 cell array
{'pears'} {'apples'} {'plums'} {'peaches'} {'oranges'} {'grapes'}

その他の回答 (1 件)

Eric Delgado
Eric Delgado 2022 年 12 月 7 日
You could write a simple loop...
string_1 = {'apples' 'pears' 'plums' 'oranges' 'peaches' 'grapes'};
vector_1 = [1 3 7 8 9 10];
vector_2 = [3 1 7 9 8 10];
idx = [];
for ii = 1:numel(vector_1)
idx(ii) = find(vector_1 == vector_2(ii), 1);
end
string_2 = string_1(idx)
string_2 = 1×6 cell array
{'pears'} {'apples'} {'plums'} {'peaches'} {'oranges'} {'grapes'}

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by