Performing multiple Operating system commands in a loop

7 次查看(过去 30 天)
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 中查找有关 Parallel Computing Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by