How to use dir in a loop to be dynamic?

Hi, Sorry for a simple question. I have abc1_0.765mat ......abc50_0.7462mat How I can call the dir in a loop.
for i=1:50
A = dir('abc1*.mat');% but it also calls abc11 and I just need abc1
end
I tried A=dir(fullfile... % but I got error
Any Suggestion

 Respuesta aceptada

Cedric
Cedric el 20 de Ag. de 2015
We actually use DIR the other way around. If file names are very regular and determined by e.g. a number, we built them using SPRINTF:
for fId = 1 : 50
filename = sprintf( 'data_%02d.mat', fId ) ;
... do something ...
end
This generates names data_01.mat, data_02.mat, etc, over successive iterations. When we don't know file names, we get a directory listing using wildcards if we know a pattern, e.g.
listing = dir( 'abc*.mat' ) ;
Calling DIR once only, we get listing as a struct array whose entries contain references to all relevant files. Then we iterate over these entries:
for fId = 1 : numel( listing )
filename = listing(fId).name ;
... do something ...
end
Finally, we use FULLFILE when we need to concatenate elements of path, e.g. a folder name and a file name:
folder = 'MyData' ;
listing = dir( fullfile( folder, 'abc*.mat' )) ;
for fId = 1 : numel( listing )
fileLocator = fullfile( folder, listing(fId).name ) ;
... do something ...
end

4 comentarios

Rita
Rita el 20 de Ag. de 2015
Thanks Cedric. Actually I have more than 100000 files and around 23000( not sure) of them starts with abc1_....mat I 'd like to call all of the files which starts with abc1_...mat and do somthing and then moving to the other files which starts with abc2_...mat and so on .It ends with abc50....mat.
Cedric
Cedric el 20 de Ag. de 2015
Editada: Cedric el 20 de Ag. de 2015
Ok, then you could go for something along the following line:
% - Iterate through groups 1 to 50.
for groupId = 1 : 50
% - Get dir listing for 'abc1_*.mat', 'abc2_*.mat', ..,
% where 1, 2, .. is the group ID.
pattern = sprintf( 'abc%d_*.mat', groupId ) ;
listing = dir( pattern ) ;
% - Iterate through files of the current group.
for fileId = 1 : numel( listing )
filename = listing(fileId).name ;
% - Load MAT File and ..
loaded = load( filename ) ;
... do something ...
end
end
Rita
Rita el 20 de Ag. de 2015
Thank you so much or your great help.
Cedric
Cedric el 20 de Ag. de 2015
My pleasure.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre File Operations en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 20 de Ag. de 2015

Comentada:

el 20 de Ag. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by