MATLAB Answers

running an external program by changing input text file for every iteration in windows.

3 views (last 30 days)
Sumera Yamin
Sumera Yamin on 24 Aug 2020
Commented: Sumera Yamin on 26 Aug 2020
Hello, i want to run an external program in matlab by changing the value of a certain parameter in the input text file. I want to scan a parameter for a certain range e.g 0-1000 in steps of 10. i want my script to change input file for every iteration, call the external program, run it and save the output files. Now my problem is divided in 2 steps.
1) I am reading the input file using
fid = fopen('input.in','r+');
data = textscan(fid, '%s', 'Delimiter', '\n', 'CollectOutput', true)
fclose(fid);
now i find many options to replace strings or numbers in text file, but i want to change the following line in input file "S_xoff(1)= 0" to "S_xoff(1)=100" and "S_yoff(1)=0" to "S_yoff(1)=100". how would i tell matlab to increase the number by 100 following a certain string.
2) I call the external program to run in matlab inside a for loop, as i want to do this for many iterations. My code runs successfully for one iteration, and then it stops. The problem is that it does not loop for multiple iterations. Any help is appreciated.
  4 Comments
Sumera Yamin
Sumera Yamin on 25 Aug 2020
hi, many thanks for this. Both sprintf and strrep seems to work fine, I can see in my command window the string being replaced but they are not being saved in my text file. How would i ask matlab to save the replacement string in the original text file and close the file. I am using the following lines of code
% ------ open files and read the data in an array --------------
clc; clear;
fid = fopen ( 'input1.in' , 'r +' );
data = textscan (fid, '% s' , 'Delimiter' , '\ n' , 'CollectOutput' , true)
fclose (fid);
% -------- writing the text file and replacing text --------
fid = fopen ( 'input1.in' , 'w' );
for I = 1: length (data {1})
str = 'S_xoff (1) = 0' ;
newStr = strrep (str, '0' , '100e-6' ) % another option
end
fclose (fid);

Sign in to comment.

Accepted Answer

Rik
Rik on 25 Aug 2020
Edited: Rik on 25 Aug 2020
This should do the trick for you:
% ------ open files and read the data in an array --------------
clc; clear;
fid = fopen('input.in','r+');
data = textscan(fid, '%s', 'Delimiter', '\n', 'CollectOutput', true)
fclose(fid);
data=data{1};
% -------- replace text --------
str_to_find=sprintf('S_xoff(1)=%d',0);
str_to_paste=sprintf('S_xoff(1)=%d',100);
data=cellfun(@(x)strrep(x,str_to_find,str_to_paste),data,'UniformOutput',false);
% -------- writing the new text file --------
fid = fopen('input1.in','w');
for n = 1:numel(data)
fprintf(fid,'%s\n',data{n})
end
fclose (fid);
  9 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!