fprintf in nested for loops

14 views (last 30 days)
b
b on 10 Jun 2017
Commented: dpb on 10 Jun 2017
Trying to fopen and fprintf the multiple files in nested for loops. Able to get the file opening to work:
for i=1:3
for j=1:4
fname=['filei' num2str(i) 'j' num2str(j) '.txt'];
fidsum=j+(i-1)*4;
sprintf('fid%d',fidsum)=fopen(fname,'w');
end
end
But the fprintf part doesn't work. The following fails:
for k=1:largeNumber
for i=1:3
for j=1:4
fidsum=j+(i-1)*4;
if ((var1(k)==i) & (var2(k)==j))
fprintf(sprintf('fid%d',fidsum),'%d\n',kDependentParameter)
end
end
end
end
This also fails:
for k=1:largeNumber
for i=1:3
for j=1:4
fidsum=j+(i-1)*4;
if ((var1(k)==i) & (var2(k)==j))
fid=sprintf('fid%d',fidsum);
fprintf(fid,'%d\n',kDependentParameter)
end
end
end
end
How to use the numerically increasing fid's for multiple file writings?
  3 Comments
dpb
dpb on 10 Jun 2017
>> help fopen
fopen Open file.
FID = fopen(FILENAME) opens the file FILENAME for read access.
...
FID is a scalar MATLAB integer valued double, called a file identifier.
...

Sign in to comment.

Accepted Answer

dpb
dpb on 10 Jun 2017
"Able to get the file opening to work"
Well, no, not really. What you've done is alias sprintf to a variable by assigning it in what looks to be array indexing syntax--
>> i=1;j=1; % assign initial values
fname=['filei' num2str(i) 'j' num2str(j) '.txt']; % ok
fidsum=j+(i-1)*4; % fidsum --> 1 ok, but not sure what intend
sprintf('fid%d',fidsum)=fopen(fname,'w'); % it all goes south here...
>>
>> whos sprintf
Name Size Bytes Class Attributes
sprintf 105x1 840 double
>> which sprintf
sprintf is a variable.
>>
Do you really need all these files open at one time would be first question...but if do, keep the handles in an array...
I=3; J=4; % loop limits
fid=zeros(I,J); % preallocate to hold way too many fids at once in all likelihood
for i=1:I
for j=1:J
fname=sprintf('filei%02dj%02d.txt',i,j); % build a file name
fid(i,j)=fopen(fname,'w'); % and open a file, return fid in array
end
end
I don't know what part the fidsum variable was to play so left it out...
Now, when you're ready to write to one of these, then you'd have to know which i, j index pair you want and would write something like
fprintf(fid(i,j),fmt,variables)
but it's highly unlikely you really, really need that many files at once.
What is the actual end objective you're wanting to output? Almost certainly there's a far better way to construct the logic to do so.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!