How to edit text file in matlab?
조회 수: 24 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
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);
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 String Parsing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!