Reputation: 11
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
Upvotes: 1
Views: 51
Reputation: 362
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.
Upvotes: 1