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

14 vues (au cours des 30 derniers jours)
Ahmad Fakih
Ahmad Fakih le 17 Avr 2019
Commenté : Ahmad Fakih le 17 Avr 2019
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

Réponse acceptée

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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by