Sorting operation on a string matrix
Show older comments
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 Comments
dpb
on 5 May 2021
>> sortrows(s)
ans =
5×1 string array
"1 9:53.3"
"2 2:45.6"
"3 9:23.5"
"4 12:01.2"
"5 2:16.2"
>>
Why create such a monstrosity to begin with?
Why not read the data in as numeric and datetime and then create a formatted output if needed?
"Didnt think MATLAB can recognize numerical data within strings. "
It doesn't. MATLAB sorts purely based on character code.
Try it with any "value" greater than 10, is that really the order you want?:
s = ["2 9:53.3";
"20 9:23.5";
"1 2:16.2";
"10 2:45.6";
"3 12:01.2"]
sort(s)
". 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...
Accepted Answer
More Answers (1)
Chunru
on 5 May 2021
try the following:
s = stab(:,1) + " " + stab(:,2)
Not sure how can you get the additional digits not in the input.
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!