running an external program by changing input text file for every iteration in windows.
3 views (last 30 days)
Show older comments
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
Rik
on 25 Aug 2020
str_to_find=sprintf('S_xoff(1)= %d',0);
str_to_paste=sprintf('S_xoff(1)= %d',100);
How exactly you can use this depends a bit on your specific file, but strrep seems to make sense as one of the options.
Accepted Answer
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
Rik
on 26 Aug 2020
Edited: Rik
on 26 Aug 2020
In the future you can also run your loop definition separately:
i=0.0001:0.1:0.001;
%returns i=0.0001
So that is probably still not what you meant. But good your code is correctly now.
If you want to change the value to a non-integer: read the documentation of sprintf for your options (the format specification works the same for fprintf and mostly the same for num2str).
More Answers (0)
See Also
Categories
Find more on Characters and Strings 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!