Borrar filtros
Borrar filtros

How to edit text file in matlab?

24 visualizaciones (últimos 30 días)
Zain Shahwar
Zain Shahwar el 6 de Mzo. de 2019
Comentada: Zain Shahwar el 7 de Mzo. de 2019
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

Respuesta aceptada

Bob Thompson
Bob Thompson el 6 de Mzo. de 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);
  1 comentario
Zain Shahwar
Zain Shahwar el 7 de Mzo. de 2019
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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre String Parsing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by