Performing multiple Operating system commands in a loop

조회 수: 5 (최근 30일)
C Mitch
C Mitch 2021년 8월 11일
편집: dpb 2021년 8월 12일
I am trying to write a code that does a system operating command multiple time on a set of files in a directory.
clear
data = uigetdir ('C:\matlab\Sim 2D')
dinfo = dir(fullfile(data,'*.in'))
list={dinfo.name}
for k = 1:length(list)
!simpson RR(k).in
end
However, when i try this i just get
Error when evaluating input script RR(k).in: couldn't read file "RR(k).in": no such file or directory
repeated k times.
Any idea what i am doing wrong?

채택된 답변

Dave B
Dave B 2021년 8월 11일
When you use ! it will treat everything after as text, it won't evaluate RR(k).in
Assuming RR(k).in is a string or char:
system("simpson " + RR(k).in)

추가 답변 (2개)

Bjorn Gustavsson
Bjorn Gustavsson 2021년 8월 11일
What I typically do in situations like these is to create a "cmd_string" and then first run the loop (or a shorter loop in case of very many repeats) just displaying the string - to be sure that I've gotten it right, then run the loop for real. Something like this:
clear
data = uigetdir ('C:\matlab\Sim 2D')
dinfo = dir(fullfile(data,'*.in'))
list={dinfo.name}
for k = 1:min(length(list),12) % just the first 12 loops if list has many more elements.
cmd_str = ['simpson ',RR(k).in];
disp(cmd_str)
% !simpson RR(k).in
end
That should be enough to see that I get the right commands on the right inputs.
Then it's work-time:
for k = 1:length(list)
cmd_str = ['simpson ',RR(k).in];
[sysstat,sysres] = system(cmd_str);
!simpson RR(k).in
end
This also allows you to handle the status of the system command (sysstat) and the result if that's needed.
HTH

dpb
dpb 2021년 8월 11일
편집: dpb 2021년 8월 12일
First, you're using the command form and the ! operator, not the functional form for system() command so as the message is telling you, you are passing the literal string
'simpson RR(k).in'
to the OS, not the content of whatever the undefined struct array(?) RR contains.
One presumes the intent is actually to pass each file name found by the preceding call to dir() instead and the reference to RR is a leftover from some other code or use paradigm in which a list of files had been stored in such a struct.
data = uigetdir ('C:\matlab\Sim 2D');
dinfo = dir(fullfile(data,'*.in'));
for k = 1:numel(dinfo)
system(['simpson ' fullfile(dinfo(k).folder,dinfo(k).name])
end

카테고리

Help CenterFile Exchange에서 Search Path에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by