필터 지우기
필터 지우기

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 CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by