fprintf in nested for loops
Ältere Kommentare anzeigen
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 Kommentare
Stephen23
am 10 Jun. 2017
Ugh, no, this is the complete opposite of how to write good code. Do not try to create numbered variable names like that, it will be slow, buggy, complicated code that is hard to debug. The much better solution (as dpb showed you) is to preallocate an array and then simply use indexing.
Some beginners think that numbered variables are a good idea: it isn't. Read this to know why: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
b
am 10 Jun. 2017
dpb
am 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.
...
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!