Sorting Variables by Value
Ältere Kommentare anzeigen
I have a series of solved values I'd like to have sorted. For example,
Apple = (Apple_weight in pounds) / 2.2
Bannana = (Bannana_weight in pounds) / 2.2
Orange = (Orange_weight in pounds) / 2.2
I'd like to have these sorted by mass. In this case it doesn't matter what the mass of the apple is, just whether it is more or less than an orange. How do I get back Orange, Apple, Bannana?
*Side note: I really wish Matlab handled units*
4 Kommentare
KSSV
am 18 Mai 2020
Read about sort.
Charles Rambo
am 18 Mai 2020
Bearbeitet: Charles Rambo
am 18 Mai 2020
Stephen23
am 18 Mai 2020
"I really wish Matlab handled units"
Third-party class: https://blogs.mathworks.com/pick/2017/03/31/physical-units-in-matlab/
Symbolic toolbox: https://www.mathworks.com/help/symbolic/units-list.html
Charles Rambo
am 18 Mai 2020
Akzeptierte Antwort
Weitere Antworten (1)
Steven Lord
am 18 Mai 2020
Rather than storing your data in individually named variables, consider a table.
rng default
weights = randi(10, 3, 1);
names = ["apple"; "banana"; "coconut"];
fruits = table(weights, 'RowNames', names)
sortedFruits = sortrows(fruits)
If you had other data in your fruits table you could select which variable you want to use to sort. sortrows also accepts an input to control whether to sort ascending or descending.
fruits.age = randi(7, 3, 1)
sortedByWeight = sortrows(fruits, "weights")
sortedByAge = sortrows(fruits, "age")
sortedByDecreasingAge = sortrows(fruits, "age", "descend")
1 Kommentar
Charles Rambo
am 19 Mai 2020
Kategorien
Mehr zu Multibody Modeling finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!