running an external program by changing input text file for every iteration in windows.
조회 수: 4 (최근 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!