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

28 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Fangjun Jiang
Fangjun Jiang el 17 de Abr. de 2019
for k=1:5
FileName=sprintf('output_matlab_%d',k)
end
  3 comentarios
Walter Roberson
Walter Roberson el 17 de Abr. de 2019
FileName = sprintf('output_matlab_%d.txt', i);
f2d = fopen(FileName, 'wt');
Ahmad Fakih
Ahmad Fakih el 17 de Abr. de 2019
Thank you Walter and Fangjun!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre String Parsing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by