Problem with looping through Folder finding pattern
Show older comments
Hello everyone,
I am attempting to loop through a folder using this code:
files = dir(MyFolder);
Pattern = MyPattern % im searching for files that match a certain pattern
for i = 1 : numel(Myfolder) %loop through Myfolder
% this next line below is where the error is coming from
value = getfield(files,{i},'name') %iterate through each file in the structure, "files"
% i did this because I need a string to use in strfind below
if strfind(value,Pattern) %check to see if current file matches Pattern
f = fullfile(MyFolder,value) %construct fullpath
% do more stuff
end
end
Im not sure if this is the best approach, but the idea is to loop through MyFolder and construct a fullfile if a file matches pattern.
This is the error generated. It comes from getfield:
??? Index exceeds matrix dimensions.
Error in ==> getfield at 46
f = f(index{:});
Error in ==> UI>pushbutton2_Callback at 252
value = getfield(files,{i},'name')
Any advice on a better approach would be great.
Accepted Answer
More Answers (1)
Walter Roberson
on 18 Jul 2011
0 votes
Also if the pattern is sufficiently simple you might be able to code it using wildcards in the dir() itself. The patterns accepted on Linux and MacOS systems are usually those expressible as pure regular expressions, which is often more than enough.
3 Comments
B_Richardson
on 18 Jul 2011
B_Richardson
on 18 Jul 2011
Walter Roberson
on 18 Jul 2011
For example, in Unix-type systems you could match against
dir('2009-10-14 11-13-04_[RS]HA_[LR]L_S[123]_0006FinalData.mat')
That would overshoot a little in that it would match SHA_RL_S1 (for example) which is not one of the patterns in your list, but a fair bit of the time that would be "close enough".
In MS Windows, I do not know how finely it can be controlled, but I know you could use (e.g)
dir('2009-10-14 11-13-04_?HA_?L_S?_0006FinalData.mat')
each ? would match a single character.
Categories
Find more on Loops and Conditional Statements 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!