MATLAB Answers

How do I make two arrays go from largest to smallest?

1 view (last 30 days)
tommy sandler
tommy sandler on 28 Apr 2021
Answered: dpb on 28 Apr 2021
How do I put these in from largest to smallest?
a = [4 8 11 7];
b = ["voltage1", "voltage2", "voltage3", "voltage4"];
%this is the output I want
a = [11 8 7 4]
b = ["voltage3", "voltage2","voltage4", "voltage1"]
%this is what I tried
c = sort(a,'descend'); %this only makes these values in a greatest to smallest
%I am not sure how to make the string values go in that order

Accepted Answer

dpb on 28 Apr 2021
[a,ix] = sort([4 8 11 7],'descend'); % keep the optional original order vector when sort
b = b(ix); % use it to arrange corollary variable in same order
NB: You don't need to keep the b array at all...just generate it on the fly from the order vector.
>> b=string("Voltage"+ix.')
b =
4×1 string array

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by