Using fprintf to specify a filename for write to text file in loop

11 ビュー (過去 30 日間)
Kobye
Kobye 2013 年 10 月 20 日
回答済み: dpb 2013 年 10 月 20 日
I am creating a number of text files (or really m files) in a loop. The filenames should be sequential, having the suffix 1,2,3... I wanted to use fprintf to specify the filename in the loop. However, I get the error in line 2: "invalid filename." How can I achieve what I am trying to do? I've pasted an example code below.
for k=1:25
fid = fopen(fprintf('K_a_12_%dx.m',k),'w');
fprintf(fid, 'function [K_a_12]=K_a_12_%dx(G_a,E_a,h_a)\n',k);
fprintf(fid, 'K_a_12=zeros(10,100)\n');
for i=(1+(k-1)*10):(k*10);
for j=1:100;
fprintf(fid, 'test');
end
end
fclose(fid);
end

採用された回答

dpb
dpb 2013 年 10 月 20 日
Use sprintf instead--*fprintf* w/o a unit number writes to screen so you're left w/ nothing in the filename location.
fid = fopen(sprintf('K_a_12_%dx.m',k),'w');
I'd suggest if you're creating files w/ such numbering systems to use the leading zeros in a fixed width field for the numbering. Then you'll get a collated ordering based on numeric order instead of collating order automagically...that is, make the format string
fn = sprintf('K_a_12_%3.3dx.m',k);
fid = fopen(fn,'w');
Using the separate filename in the fopen is matter of taste; building it separately can help in debugging during development if on then wants to fold it into the fopen can...

その他の回答 (1 件)

Kobye
Kobye 2013 年 10 月 20 日
I've figured it out... had to use sprintf instead of fprintf.

カテゴリ

Help Center および File ExchangeLow-Level File I/O についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by