fprintf in nested for loops
古いコメントを表示
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 件のコメント
Stephen23
2017 年 6 月 10 日
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
2017 年 6 月 10 日
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.
...
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!