running an external program by changing input text file for every iteration in windows.
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Rik
2020-8-25
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.
采纳的回答
Rik
2020-8-25
编辑:Rik
2020-8-25
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 个评论
Rik
2020-8-26
编辑:Rik
2020-8-26
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).
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!