fprintf in nested for loops
Afficher commentaires plus anciens
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 commentaires
Stephen23
le 10 Juin 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
le 10 Juin 2017
dpb
le 10 Juin 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.
...
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!