Sorting operation on a string matrix
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi everyone,
My code for sorting string. Question in comment:
s = ["1 9:53.3";
"3 9:23.5";
"5 2:16.2";
"2 2:45.6";
"4 12:01.2"]
s = split(s," ",2);
stab = array2table(s);
stab.s1 = double(stab.s1);
stab = sortrows(stab,"s1","ascend");
stab.s1 = string(stab.s1);
stab = table2array(stab)
% Question : How do I get the sorted matrix as a 5X1 matrix now?
Required sorted output matrix :
s =[ "1 9:53.334"
"2 2:45.623"
"3 9:23.545"
"4 12:01.213"
"5 2:16.245"]
Suggestions, if any, for better/more effficient ways to this string data are welcome.
Thanks for your time in advance.
5 commentaires
dpb
le 5 Mai 2021
Modifié(e) : dpb
le 5 Mai 2021
". it sorts data as 1,10,11...2,20,21... "
Of course it does; that was the point of asking why you're so stuck on trying to treat numeric data as character...note again that Stephen's solution has to convert to numeric first (as he also points to a better storage design) so why not just do that from the git-go instead of making it more difficult than needs be?
There is a lexical sort (and why TMW hasn't builtin one is anybody's guess) on FEX altho I don't have the link right now at hand...
Réponse acceptée
Stephen23
le 5 Mai 2021
Modifié(e) : Stephen23
le 5 Mai 2021
s = ["1 9:53.3";
"3 9:23.5";
"5 2:16.2";
"2 2:45.6";
"4 12:01.2"];
[~,X] = sort(str2double(extractBefore(s,' ')));
out = s(X,:)
Note that much better data design would store numeric data as a numeric type.
6 commentaires
dpb
le 6 Mai 2021
Modifié(e) : dpb
le 6 Mai 2021
>> s=split(s);
>> data=table(str2double(s(:,1)), ...
duration(s(:,2),'InputFormat','mm:ss.S','Format','mm:ss.S'), ...
'VariableNames',{'N','T'})
data =
5×2 table
N T
_ _______
1 09:53.3
3 09:23.5
5 02:16.2
2 02:45.6
4 12:01.2
>> sortrows(data,'N')
ans =
5×2 table
N T
_ _______
1 09:53.3
2 02:45.6
3 09:23.5
4 12:01.2
5 02:16.2
>>
Or, alternatively, if were interested in the time/duration
>> sortrows(data,'T')
ans =
5×2 table
N T
_ _______
5 02:16.2
2 02:45.6
3 09:23.5
1 09:53.3
4 12:01.2
>>
Nothing could be easier; NB: the table is a wonderfully powerful container for mixed data types; much more flexible than just a cell array and far more convienent than holding in either separate arrays or to try to machinate on text when it really isn't text...
If you were to have begun with a text file instead of a string array, you surely would have used readtable or similar tool to import as the type of data in the file; the message is to treat the source text the same way despite its origin.
Plus de réponses (1)
Chunru
le 5 Mai 2021
try the following:
s = stab(:,1) + " " + stab(:,2)
Not sure how can you get the additional digits not in the input.
0 commentaires
Voir également
Catégories
En savoir plus sur Characters and Strings 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!