Sorting operation on a string matrix
이전 댓글 표시
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
dpb
2021년 5월 5일
>> 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...
채택된 답변
추가 답변 (1개)
Chunru
2021년 5월 5일
try the following:
s = stab(:,1) + " " + stab(:,2)
Not sure how can you get the additional digits not in the input.
카테고리
도움말 센터 및 File Exchange에서 Large Files and Big Data에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!