Ranking Variables by Value
Show older comments
Dear all,
let's assume I have a basket of 4 different kinds of fruits (Apples, Oranges, Bananas, Pears).
n_a
n_o
n_b
n_p
tell me the number (n) of each fruit that I have.
If my basket is full, I would like to sell the rest of the fruits that I do not need. However, every fruit has a different value (price = p). Let's say
p_a = 4
p_o = 2
p_b = 1
p_p = 0
Let's say, I have x too many fruits, so
toomanyfruits = x
Now, I would first like to sell the ones, I get the most value from (I can only sell as many as I have). If toomanyfruits is still > 0, I would like to sell the ones which are second most valuable etc. pp..
So, I tried to use the command sort, but I have the problem that I do not need the sorted values, but the names of that fruit which has the highest value to be able to then call it for ranking. I tried some different things, but do not seem to get the right thing.
Some help would be highly appreciated :-)
With kind regards
Maria
Accepted Answer
More Answers (1)
Steven Lord
on 27 May 2020
You've made this a bit harder on yourself than it needs to be by defining individual variables for the counts and prices of each fruit. Instead I would define three variables.
fruitCounts = randi([0 5], 1, 4) % Random numbers (between 0 and 5) of each type of fruit
fruitPrices = randi([0 5], 1, 4) % Random prices (between 0 and 5) of each type of fruit
fruitNames = ["apple", "orange", "banana", "pear"] % Fruit names
Now when you sort fruitPrices as Jeff Miller suggested, you can directly see what type of fruit that is and how much of it you have.
[sortedPrices, priceOrder] = sort(fruitPrices);
sortedPrices
fruitCounts(priceOrder)
fruitNames(priceOrder)
1 Comment
Maria Hart
on 27 May 2020
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!