フィルターのクリア

How to edit text file in matlab?

24 ビュー (過去 30 日間)
Zain Shahwar
Zain Shahwar 2019 年 3 月 6 日
コメント済み: Zain Shahwar 2019 年 3 月 7 日
Hi Everyone,
I have a text file having Gcode in it. I want to change the Gcode into a matlab readable file(.m) e.g I have these two line in .txt file:
G1 X138.22 Y13.96 F3500.00
G1 X138.22 Y153.50 F3500.00
I want to edit these two line and make it like as shown below:
G1 = [138.22 13.96]
G2 = [138.22 153.50]
I have another text file having the Gcode of about 100+ lines. So, I am looking for a matlab function that does this automatically without having to change my file manually.
Thank you

採用された回答

Bob Thompson
Bob Thompson 2019 年 3 月 6 日
I don't know that it is worth the effort to actually edit a text file with MATLAB, but it is certainly possible to read it, edit the values in MATLAB, and then create a new version of the file.
fid = fopen('myfile.txt');
text = textscan(fid,'%s','delimiter','\n');
% You will need to adjust this to fit more than your example
lines = find(cellfun(@(x) strcmp(x(1),'G'),text)); % Looking for lines which start with G. This may not work
for i = 1:length(lines);
nums = regexp(text{lines(i)},'G\d+ X(\d+.\d*) Y(\d+.\d*) .*','tokens'); % Locate numbers in line
coords = [str2num(nums{1}{1}) str2num(nums{1}{2})]; % Convert to numbers from strings
text{lines(i)} = [text{lines(i)}(1:3),' = [',num2str(coords),']']; % Replace the line with new format
end
fclose(fid);
fid = fopen('myfile.txt','w'); % Open as writable file (overwrites old stuff)**************
fprintf(fid,'%s\n',text{:});
fclose(fid);
  1 件のコメント
Zain Shahwar
Zain Shahwar 2019 年 3 月 7 日
THank you very much for your help. I applied that method with little errors it worked fine.
I have also found one solution, I imported .txt file from matlab import data tool and sorted the file through that and generated a script file.
Now I am able to convert every single column (numeric text) into numbers. I have attached the script file "Untitled_new.m". Please have a look.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by