フィルターのクリア

How to include a variable in "fopen" file name in a For loop?

29 ビュー (過去 30 日間)
Ahmad Fakih
Ahmad Fakih 2019 年 4 月 17 日
コメント済み: Ahmad Fakih 2019 年 4 月 17 日
Dear members,
This code edits a certain number in an input text and generates a new output file containing the new edited number. I want to generate many output files but the problem is that each time a new output file is generate it replaces the previous one since they will have the same name. I want to include a variable in the name that changes each time the code loops.
So I need to edit this line: f2d = fopen('output_matlab_i.txt','wt') where i will be variable from 1 to s and thus we will get: output_matlab_1, output_matlab_2, output_matlab_3...
Any help?
Thank you!
phi_rnd=lognrnd(log((m^2)/sqrt(std^2+m^2)),sqrt(log(std^2/(m^2)+1)),1,n)
indices = find(abs(phi_rnd)<28);
phi_rnd(indices) = [];
s=size(phi_rnd,2);
for i=1:s
vec=zeros(1,2);
vec = [phi_rnd(1,i),phi_rnd(1,i)];
cnt = 0;
rgx = '^(\s*\S+\s+)(\S+)(.+gamma.+)$';
f1d = fopen( 'input_matlab.txt','rt');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
f2d = fopen('output_matlab.txt','wt');%>>>>>This is the line to be edited
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while ~feof(f1d)
str = fgetl(f1d);
tkn = regexp(str,rgx,'once','tokens');
if ~isempty(tkn)
cnt = cnt+1;
str = sprintf('%s%#.14E%s',tkn{1},vec(cnt),tkn{3});
end
fprintf(f2d,'%s\n',str);
end
fclose(f1d);
fclose(f2d);
end

採用された回答

Fangjun Jiang
Fangjun Jiang 2019 年 4 月 17 日
for k=1:5
FileName=sprintf('output_matlab_%d',k)
end
  3 件のコメント
Walter Roberson
Walter Roberson 2019 年 4 月 17 日
FileName = sprintf('output_matlab_%d.txt', i);
f2d = fopen(FileName, 'wt');
Ahmad Fakih
Ahmad Fakih 2019 年 4 月 17 日
Thank you Walter and Fangjun!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by