Create a .run file with 1000 sequenced commands

1 回表示 (過去 30 日間)
Mohammed Hadi
Mohammed Hadi 2019 年 2 月 14 日
回答済み: Rik 2019 年 2 月 14 日
Hi
I need to create a run file, I have several lines of code that I need a run file execute over a number of (.dat) files.
a simple, one run looks like this
reset;
option solver cplex;
model ABC.mod;
data a_1.dat;
solve;
What I need is to repeat that same commands with only 1 modification. each new time using a new (.dat) file.. I have the dat files numbered (i.e. a_1.dat, a_2.dat ,...., a_1000.dat)
I wrote the following code, however, I keep getting 1 file with 1 set of commands.
clear all;
TNOR=6; % total number of runs (i.e. total number of files the run file will go over one by one
for i = 1:TNOR
L1 = 'reset;';
L2 = 'option solver cplex';
L3 = 'model ABC.mod;';
s1 = 'data a_' ;
s2 = (num2str('%d', i)) ;
s3 = '.dat ;';
L4=strcat(s1,s2,s3);
L5= 'solve;';
FID=fopen('runfile.run','w'); % file identifier
fprintf(FID,'%s \n',L1, L2, L3); % print data of first file
fprintf(FID,'%s \n',L4);
fprintf(FID,'%s \n',L5);
fprintf(FID,'\n');
fprintf(FID,'\n');
end
fclose all;
  1 件のコメント
Mohammed Hadi
Mohammed Hadi 2019 年 2 月 14 日
solved it ;)
I was writing to the file not appending the new text..
Also I had a wrong way to add the number of the .dat file
the following are the two lines that I had a problem with
s2 = (num2str(i)) ;
FID=fopen('runfile.run','a'); % file identifier

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

採用された回答

Rik
Rik 2019 年 2 月 14 日
A better solution is to fopen your file before your loop, so it is wiped before your first iteration. You should also use the sprintf command for visual clarity or use the fprintf directly. It is also better to make a habbit of moving static assignments out of the loop.
Also, using i or j as loop iterator is generally not a good idea due to the possible confusion with the imaginary unit, in which case you should use 1i or 1j.
clear variables;
TNOR=6; % total number of runs (i.e. total number of files the run file will go over one by one
FID=fopen('runfile.run','w'); % file identifier
L=cell(1,5);
L{1{} = 'reset;';
L{2} = 'option solver cplex';
L{3} = 'model ABC.mod;';
L{5}= 'solve;';
for ii = 1:TNOR
L{4}=sprintf('data a_%d.dat \n',ii);
fprintf(FID,'%s \n',L{:});% print data
end
fclose all;

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by