How to run a .m script for all folders in a directory?
Show older comments
Hello,
I have a question about a code. I have a .m script. This script requires 2 inputs in a folder in order to run. But I would like to run this .m script for all folders in a directory (path). The reason is that each input has different numbers so different results of each run of .m code will arise.
Could you please help me?
10 Comments
Rik
on 22 Apr 2021
Why are you using scripts? This would probably be easy with a function that accepts a path.
Ivan Mich
on 22 Apr 2021
Jonas
on 22 Apr 2021
if i understood you correctly your script simply works in the current directory. what you can do is that you add your script to your search path ( addpath() ) and then navigate to the folders using cd() and calling your script
Ivan Mich
on 22 Apr 2021
e.g. if all folders in which you want to run the script are on the same director level you could use something like
addpath('MyScript.m')
dirContent=dir(); % get content of current directory
dirContent(~[dirContent.isdir])=[]; % delete entries that are no folders
dirContent(1:2)=[]; % delete '.' and '..' directory
folders={dirContent.name} % get folder names
for dirNr=1:numel(folders)
cd(folders{dirNr}); % change dir to specified folder
MyScript();
cd ..; % go back up a level
end
NOTE: this loop should not be changed to a parfor loop because changing directories causes some issues in that case
Rik
on 22 Apr 2021
You really should avoid messing with the path only to read/process files.
You should convert your script to a function that accepts a path. If you need help with that, feel free to comment with your issues. If you attach your script to a comment we may be able to give you more targeted advice.
Ivan Mich
on 22 Apr 2021
Ivan Mich
on 22 Apr 2021
Rik
on 22 Apr 2021
You should convert your matlab code to a function that accepts a path.
You should not use scripts for actual work. You should avoid cd, it is almost never required.
Attach your script so we can suggest edits. If it is just reading two files, that should not be hard.
Stephen23
on 22 Apr 2021
"What should I do?"
Use functions.
Use absolute/relative filenames.
Avoid CD.
Avoid scripts for serious work (i.e. for anything versatile, expandable, repeatable, reliable, testable, ...)
Answers (0)
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!