1

So I have a string array with the names of 5 history textbooks, and a list below containing their consecutive prices in dollars. I want to create a loop function that sorts the prices and lists the names of the textbooks as well. I know how to create a loop that sorts the prices, but I don't know how to make the function list the textbook each price belongs to. Any help would be greatly appreciated. Thanks

%LIST OF TEXTBOOKS

TB = ["1. America Past and Present - Divine","2. America's History - Henretta","3. Unfinished Nation - Brinkley","4. Out of Many - Faragher","5.The American Pageant - Kennedy"];

%LIST CONTAINING TEXTBOOK PRICES IN DOLLARS 

cost = [118 120 97 102 89]; 

%HERE I WANT TO WRITE A FUNCTION THAT RETURNS THE TEXTBOOK NAME AND IT'S PRICE 
2
  • Show us what you have already done Commented Sep 29, 2018 at 1:46
  • This sorts the cost, but that’s all I can figure out how to do for i = 1:length(cost) [changeVal(i),x] = min(cost); cost(x) = []; end cost = changeVal Commented Sep 29, 2018 at 2:15

1 Answer 1

1

If you want to stick with your loop code, you can append to an initially empty new list the TB(x), (after you find the min inside the loop) , and finally overrun TB by that list, as you do for 'cost'.

Alternatively, you can for example use MATLAB's sort() function, retrieve its indices and apply them on TB, like:

[~, I] = sort(cost) ;
TB = TB(I) ;

Also, if you plan to use the book-cost structure a lot, you can define them as a table and then you can use MATLAB's sortrows() function, that can be applied to tables. See the doc, in particular - the sorting by table's variables.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.