Sorting Variables by Value
显示 更早的评论
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 个评论
KSSV
2020-5-18
Read about sort.
Charles Rambo
2020-5-18
编辑:Charles Rambo
2020-5-18
Stephen23
2020-5-18
"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
2020-5-18
采纳的回答
更多回答(1 个)
Steven Lord
2020-5-18
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")
类别
在 帮助中心 和 File Exchange 中查找有关 Multibody Modeling 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!