Sorting a string according to the values of a vector of type double

2 ビュー (過去 30 日間)
L'O.G.
L'O.G. 2022 年 12 月 9 日
回答済み: Les Beckham 2022 年 12 月 9 日
I have a vector A with numbers of type double. Two of the values of A are the same, e.g.,
A = [1.1 2.3 4.4 2.3 5.1];
I also have a corresponding string, e.g.,
vegetables = {'carrots' 'lettuce' 'cabbage' 'parsley' 'tomatoes'};
I want to order A in increasing values and re-arrange the string accordingly. If a value appears more than once, as is the case here, how do I make sure it's still counted? So here in this simple example I should end up with:
A = [1.1 2.3 2.3 4.4 5.1];
vegatables={'carrots' 'lettuce' 'parsley' 'cabbage' 'tomatoes'};
I tried to do this by
[~,idx] = ismember(sort(A),A);
vegatables_ordered = vegetables(idx);
A_ordered = sort(A);
But that doesn't get the string right. How do I do this? There won't be duplicate values in all cases, but I want to account for this possibility shown here.

採用された回答

Les Beckham
Les Beckham 2022 年 12 月 9 日
It should be as simple as this unless I misunderstand what you are expecting.
A = [1.1 2.3 4.4 2.3 5.1];
vegetables = {'carrots' 'lettuce' 'parsley' 'cabbage' 'tomatoes'};
[As,idx] = sort(A)
As = 1×5
1.1000 2.3000 2.3000 4.4000 5.1000
idx = 1×5
1 2 4 3 5
vegetables(idx)
ans = 1×5 cell array
{'carrots'} {'lettuce'} {'cabbage'} {'parsley'} {'tomatoes'}

その他の回答 (1 件)

Steven Lord
Steven Lord 2022 年 12 月 9 日
Take a look at the second output from the sort function.

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by