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

24 views (last 30 days)
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

Accepted Answer

Fangjun Jiang
Fangjun Jiang on 17 Apr 2019
for k=1:5
FileName=sprintf('output_matlab_%d',k)
end

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!