How to output every iteration of a for loop to a .txt file using fprintf?

3 次查看(过去 30 天)
Locations=[1 2 ; 2 3 ; 4 5];
P1=[1 2 3];
input= [3 4 5]
fid= fopen('GCode.txt','w');
for x = P1(1) : P1(end)
fprintf(fid,'G0 X%d Y%d Z0 \n',Locations(x,1),Locations(x,2));
for y = 1:input(x);
fprintf(fid,'G0 Z1 \n G0 Z0');
end
end
fclose(fid);
I would like to output every location into a .txt file in a list as well as a reapeting string as many times as the value in the location in the input vector. Output I want: Iteration 1:
G0 X1 Y2 Z0 G0 Z1 G0 Z0
G0 Z1 G0 Z0
G0 Z1 G0 Z0
Iteration 2:
G0 X2 Y3 Z0 G0 Z1 G0 Z0
G0 Z1 G0 Z0
G0 Z1 G0 Z0
G0 Z1 G0 Z0
Iteration 3:
G0 X4 Y5 Z0 G0 Z1 G0 Z0
G0 Z1 G0 Z0
G0 Z1 G0 Z0
G0 Z1 G0 Z0
G0 Z1 G0 Z0
However when running this code, it only outputs the final iteration of the for loop instead of the result of every iteration in a list to the .txt file. Any help would be greatly appreciated. (The purpose of this code is to automatically generate G-Codes for a CNC machine based upon input X Y coordinates)
  3 个评论
Image Analyst
Image Analyst 2013-10-2
编辑:Image Analyst 2013-10-2
I guess you didn't notice that he used input for an variable name. It should be replaced with a non-reserved word like in my code below. Plus, this should have been an answer, not a comment, so you could get credit for it.

请先登录,再进行评论。

回答(1 个)

Image Analyst
Image Analyst 2013-10-2
This code will do that:
Locations=[1 2 ; 2 3 ; 4 5]
P1=[1 2 3];
repeatCount = [3 4 5]
% fid= fopen('GCode.txt','w');
fid=1; % To command window for testing.
for x = P1(1) : P1(end)
fprintf(fid,'G0 X%d Y%d Z0 G0 Z1 G0 Z0\n',Locations(x,1),Locations(x,2));
for y = 1 : (repeatCount(x) - 1);
fprintf(fid,'G0 Z1 G0 Z0\n');
end
end
% fclose(fid);
Comment out the fid line when you're done testing it and put back in the fopen() and fclose() to do it to a file.

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by