how to loop through subfolders and apply a particular function

4 visualizaciones (últimos 30 días)
Newman el 6 de Jul. de 2016
Editada: Stephen23 el 17 de Mayo de 2019
Hello I have 40 subfolders in folder.And each of these subfolder contrains 10 images in pgm format. Suppose I want to aply normalisation to all these images using my normalize.m fucntion.How do i loop into all these subfolders and then apply fucntion to each of these images and also overwrite them on the same location .

Respuestas (2)

Thorsten el 6 de Jul. de 2016
You get use my function getfn to get all pgm images in all subfolders
fn = getfn(mkdir, 'pgm$')
And then you work on the files
for i = 1:numel(fn)
I = imread(fn{i});
In = yournormalisation(I);
imwrite(In, fn{i});
With getfn given by
function filenames = getfn(mydir, pattern)
%GETFN Get filenames in directory and subdirectories.
% Example: Get all files that end with 'txt' in the current directory and
% all subdirectories
% fn = getfn(pwd, 'txt$')
% 2016-07-06
if nargin == 0
mydir = pwd;
% computes common variable FILENAMES: get all files in MYDIR and
% recursively traverses subdirectories to get all files in these
% subdirectories:
% if PATTERN is given, select only those files that match the PATTERN:
if nargin > 1
idx = ~cellfun(@isempty, regexp(filenames, pattern));
filenames = filenames(idx);
function getfnrec(mydir)
% nested function, works on common variable FILENAMES
% recursively traverses subdirectories and returns filenames
% with path relative to the top level directory
d = dir(mydir);
filenames = {d(~[d.isdir]).name};
filenames = strcat(mydir, filesep, filenames);
dirnames = {d([d.isdir]).name};
dirnames = setdiff(dirnames, {'.', '..'});
for i = 1:numel(dirnames)
fulldirname = [mydir filesep dirnames{i}];
filenames = [filenames, getfn(fulldirname)];
end % nested function
  1 comentario
Stephen23 el 17 de Mayo de 2019
Editada: Stephen23 el 17 de Mayo de 2019
This code is incorrectly commented, is not well written, and should be avoided.
  • Use of string concatenation instead of the recommended fullfile.
  • Totally pointless nested function. Although the code comments state that the nested function is used for recursion, in fact the code calls the main function and not the nested function. The nested function is actually called only once by the main function, and it serves absolutely no purpose (apart from making the code more complex).
  • The use of regexp does not allow for any special characters in the pattern. For example the dot/period, square brackets, parentheses, etc., will be incorrectly handled. This could be resolved using regexptranslate or a pattern to dir itself.
Better recursive functions can (possibly) be found on FEX:
And since MATLAB R2016b dir can also search subfolders recursively:

Iniciar sesión para comentar.

Stephen23 el 17 de Mayo de 2019
Editada: Stephen23 el 17 de Mayo de 2019
A simple function which correctly handles special characters in the pattern and actually calls the nested function recursively:
function [files,paths] = recdir(mydir,pattern)
% Recursively list filenames in all subdirectories. Pattern uses DIR syntax.
% Example: [N,P] = recdir(pwd, '*.txt')
files = {};
paths = {};
function nestdir(P)
S = dir(fullfile(P,pattern));
files = [files,{}];
paths = [paths,repmat({P},1,numel(S))];
S = dir(fullfile(P,'*'));
C = setdiff({S([S.isdir]).name},{'..','.'});
for k = 1:numel(C)
And tested (the test folder structure is attached as zip file):
>> [N,P] = recdir(pwd, '*[].txt')
N =
'b[].txt' 'e[].txt' 'j[].txt'
P =
'C:\MATLAB\working' 'C:\MATLAB\working\A' 'C:\MATLAB\working\C\D'


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!

Translated by