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

5 ビュー (過去 30 日間)
Phil
Phil 2013 年 10 月 2 日
コメント済み: Duke 2013 年 10 月 2 日
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.
Duke
Duke 2013 年 10 月 2 日
Oops, guess my eyes are a little too strained to catch that. My bad

サインインしてコメントする。

回答 (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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by