fprintf in nested for loops

조회 수: 2 (최근 30일)
b
b 2017년 6월 10일
댓글: dpb 2017년 6월 10일
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
b
b 2017년 6월 10일
Thanks. Did not realize that indexing can be used for file identifiers also.
dpb
dpb 2017년 6월 10일
>> 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.
...

댓글을 달려면 로그인하십시오.

채택된 답변

dpb
dpb 2017년 6월 10일
"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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by