How to edit text file in matlab?
19 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Bob Thompson
on 6 Mar 2019
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);
More Answers (0)
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!