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

조회 수: 27 (최근 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 CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by