MATLAB Answers

Need to sort the number in the increasing order using MATLAB script, shown as a sample text file.

3 ビュー (過去 30 日間)
Ravi Shankar
Ravi Shankar 2019 年 11 月 29 日
Commented: Ravi Shankar 2019 年 12 月 3 日
The current avilable pattern is as follows,
0.0,A
2.0,B
5.00,C
0.10,D
5.00,E
0.10,F
1.00,G
0.10,H
10.00,I
0.10,J
2.0,K
2.0,L
2.0,M
5.00,N
0.10,O
10.00,P
0.10,Q
The required pattern is as follows,
0.0,A
0.10,D
0.10,F
0.10,H
0.10,J
0.10,O
0.10,Q
1.00,G
2.0,B
2.0,K
2.0,L
2.0,M
5.00,C
5.00,E
5.00,N
10.00,I
10.00,P

  0 件のコメント

サインイン to comment.

件の回答 (2)

Stephen Cobeldick
Stephen Cobeldick 2019 年 11 月 29 日
編集済み: Stephen Cobeldick 2019 年 11 月 29 日
You could download my FEX submission natsort:
And then import your file into a cell array of character vectors C:
C = regexp(fileread('new.txt'),'\S+','match');
D = natsort(C,'\d+\.?\d*'); % sort into the requested order.
Where D contains the sorted character vectors, which you can check:
>> D(:)
ans =
'0.0,A'
'0.10,D'
'0.10,F'
'0.10,H'
'0.10,J'
'0.10,O'
'0.10,Q'
'1.00,G'
'2.0,B'
'2.0,K'
'2.0,L'
'2.0,M'
'5.00,C'
'5.00,E'
'5.00,N'
'10.00,I'
'10.00,P'
If you want, save it to file:
[fid,msg] = fopen('out.txt','wt');
assert(fid>=3,msg)
fprintf('%s\n',D{:});
fclose(fid);

  3 件のコメント

Ravi Shankar
Ravi Shankar 2019 年 12 月 2 日
Hi Stephen,
Thanks for the information that you provided.
I am able to read the content inside Text File which this command,
C = regexp(fileread('new.txt'),'\S+','match');
After that when i run this below command i am getting following error,
D = natsort(C,'\d+\.?\d*');
Undefined function or variable 'natsort'.
Can you help me on this issue.
Thank you,
Stephen Cobeldick
Stephen Cobeldick 2019 年 12 月 2 日
"Can you help me on this issue."
Of course. Here is the very first sentence of my answer:
"You could download my FEX submission natsort:"
Did you DOWNLOAD my FEX submssion from the link that I gave you? You will then need to unzip it into the current folder (or somewhere on the MATLAB Search Path).

サインイン to comment.


Andrei Bobrov
Andrei Bobrov 2019 年 11 月 29 日
T = readtable('new.txt')
T = sortrows(T)
writetable(T,'new2.txt','delimiter',',','WriteVariableNames',0)

  2 件のコメント

Stephen Cobeldick
Stephen Cobeldick 2019 年 11 月 29 日
Note that this method changes the numeric data format, the output file looks like this:
0.1,D
0.1,F
0.1,H
0.1,J
0.1,O
0.1,Q
1,G
2,B
2,K
2,L
2,M
5,C
5,E
5,N
10,I
10,P
Given the varaible number of trailing digits, it would be fiddly to make this work using writetable. The answer I provided gives the data in exactly the format shown in the question (i.e. unchanged from the input format).

サインイン to comment.

サインイン してこの質問に回答します。


Translated by