Performing multiple Operating system commands in a loop

5 views (last 30 days)
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?

Accepted Answer

Dave B
Dave B on 11 Aug 2021
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)

More Answers (2)

Bjorn Gustavsson
Bjorn Gustavsson on 11 Aug 2021
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 on 11 Aug 2021
Edited: dpb on 12 Aug 2021
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

Categories

Find more on Search Path 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!