Script for running all .m files in a large file folder with sub folders.

41 visualizaciones (últimos 30 días)
LAUREN
LAUREN el 18 de Nov. de 2024 a las 17:21
Editada: Image Analyst el 18 de Nov. de 2024 a las 23:40
Trying to create a script that will run over 100 subfolders with 2-3 .m scripts in each subfolder.
  1 comentario
Stephen23
Stephen23 el 18 de Nov. de 2024 a las 19:21
"Trying to create a script that will run over 100 subfolders with 2-3 .m scripts in each subfolder. "
Ugh, that sounds terrible.
I am guessing that you actually have 100 subfolders containing data files, and that you (incorrectly) think that you need to copy some MATLAB scripts/functions into each of those data folders in order to process those data files. If that is the case then don't do that. The much better solution is to save your scripts/functions just once in their own folder (on the MATLAB Search Path) and then loop over all of the files in the subfolders:
Note that all MATLAB functions that import/export file data accept absolute/relative filenames. You will find that FULLFILE is most useful for this task.
On the other hand, if you really do have hundreds of unique scripts/functions that have all been written without any unifying script... then good luck.

Iniciar sesión para comentar.

Respuestas (1)

Image Analyst
Image Analyst el 18 de Nov. de 2024 a las 18:12
Editada: Image Analyst el 18 de Nov. de 2024 a las 23:40
OK. Good luck with it.
You might find the FAQ: helpful: Process a sequence of files
To get a list of all m-files in your top level folder and within subfolders you can do
pattern = fullfile(topLevelFolder, '\**\*.m');
allMFiles = dir(pattern)
Let us know if you need help. Full Demo:
% Specify the top level folder where the script files live.
topLevelFolder = pwd; % or 'C:\Users\yourUserName\Documents\My Pictures' or whatever you want.
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(topLevelFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', topLevelFolder);
uiwait(warndlg(errorMessage));
topLevelFolder = uigetdir(); % Ask for a new one.
if topLevelFolder == 0
% User clicked Cancel
return;
end
end
% Get a list of all files in the folder with the desired file name pattern
% plus in subfolders of the top level folder.
filePattern = fullfile(topLevelFolder, '**\*.m'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
% Construct this file name.
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'About to run %s\n', fullFileName);
% Run the script.
run(fullFileName);
fprintf(1, 'Done running %s\n', fullFileName);
end

Productos


Versión

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by