How can I recursively process files in subdirectories using MATLAB?
41 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
MathWorks Support Team
el 27 de Jun. de 2009
Editada: MathWorks Support Team
el 12 de Mayo de 2023
How can I recursively process files in subdirectories using MATLAB?
I have files located in multiple subdirectories within a directory. I would like to be able to process the data in each subdirectory using the same functions. How can I do this without having to manually run the code in each directory?
Respuesta aceptada
MathWorks Support Team
el 12 de Mayo de 2023
Editada: MathWorks Support Team
el 12 de Mayo de 2023
The first task is to get a list of all the desired files in all of the subdirectories.
One option to do this is to use a "system" call to access the Operating System recursive directory search call. For example to get all ".m" files in "C:\Program Files\MATLAB" on Windows:
baseDir = 'C:\"Program Files"\MATLAB'
[status, list] = system(['dir/s/b ' baseDir '*.m']);
This produces a different output format than "dir" but it can be parsed to perform the same tasks.
Another option is to process the files in a directory hierarchy through the use of recursive functions. The general format is:
1) Call the recursive function with the name of a directory.
2) Use the "dir" function to obtain a listing of the directory.
3) Loop through the entries in the listing.
4) If an entry is a directory, then call the function recursively, passing the subdirectory's name as the directory to process.
5) If an entry is not a directory, then store the file path including filename.
Please find an example file in the MATLAB File Exchange submission "subdir":
Or the example file on the File Exchange "rdir":
Note that MathWorks does not guarantee or warrant the use or content of these submissions. Any questions, issues, or complaints should be directed to the contributing author.
Once a list of files has been gathered through one of these methods, the files can be processed.
0 comentarios
Más respuestas (1)
lvn
el 11 de Mzo. de 2020
It is high time Matlab updates some of the official answers, as many are outdated.
This is an example, as of R2016b, no need for external tools:
files=dir('C:\temp\**\*.txt');
for k=1:length(files)
fn=fullfile(files(k).folder, files(k).name);
%process the file fn here
end
0 comentarios
Ver también
Categorías
Más información sobre File Operations en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!