MATLAB: Ranking Variables by Value

ranksort

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

Best Answer

You might find the second output of the sort command useful. E.g.
fruitVals = [p_a p_b p_o p_p];
[~, idxOrder] = sort(fruitVals);
Now idxOrder(1) will be the location (1-4) in fruitVals of the lowest-price fruit, idxOrder(2) the second-lowest, and so on.