Sort variables form lowest to largest but by keeping their name

12 vues (au cours des 30 derniers jours)
Matteo Babin
Matteo Babin le 9 Mai 2020
Commenté : dpb le 10 Mai 2020
Hi,
I'm looking for a way to sort some variables from the smallest value to the largest, but I would like to have the variable's names instead of their value as the output. For example:
a = 5; b = 10; c = 6;
Ans = sort( [ a b c ] )
In this case the Command Window will show me " Ans = 5 6 10" but I would like it to show " Ans = a c b"
How can I do that without using a "if" to sort them by name afterwards, which could become very long in the case of many variables?
Thanks for your answer!

Réponses (2)

dpb
dpb le 9 Mai 2020
Per usual, the way in MATLABB is to not used explicitly named variables -- use an array and if you need some auxiliary name/id to go with them, carry that along as a corollary variable.
data=[5 10 6];
names=cellstr(['a':'c'].');
[~,ix]=sort(data);
>> names(ix)
ans =
3×1 cell array
{'a'}
{'c'}
{'b'}
>>

Stephen23
Stephen23 le 9 Mai 2020
Using separate variables is an approach that will force you into writing slow, inefficient, complex code. A much better use of MATLAB would be to use arrays to store your data, which is exactly what MATLAB was designed for.
A table makes your task very simple:
>> names = {'a';'b';'c';};
>> values = [ 5; 10; 6];
>> T = table(names,values)
T =
names values
_____ ______
'a' 5
'b' 10
'c' 6
>> T = sortrows(T,'values')
T =
names values
_____ ______
'a' 5
'c' 6
'b' 10
  1 commentaire
dpb
dpb le 10 Mai 2020
Good idea to put into the table, Stephen... +1

Connectez-vous pour commenter.

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by