How to run a for loop with a string as loop index?
6 views (last 30 days)
Show older comments
I want to run a loop for opening all files in a directory, and accessing each file's name.Here's my code:
AllFiles=dir('');
TotalFiles=size(AllFiles,1)-2; %skiping first two entries are '.' and '..'
FolderPath=AllFiles(1).folder; %same folder for all files
for i= AllFiles(3).name : AllFiles(TotalFiles).name
FilePath=strcat(FolderPath,'/',i);
end
2 Comments
Stephen23
on 11 Oct 2018
Edited: Stephen23
on 11 Oct 2018
Do NOT do this:
TotalFiles=size(AllFiles,1)-2; %skiping first two entries are '.' and '..'
This is fragile code that incorrectly assumes that the first two elements of the structure refer to the folders '.' and '..'. This is NOT documented, depends on the OS, and is not necessarily correct.
A more reliable way to is to test the names explicitly and remove them using indexing:
S = dir('');
X = ismember({S.name},{'.','..'})
S = S(~X);
Also you should use fullfile rather than string concatenation:
S = dir('.');
S = S(~ismember({S.name},{'.','..'}));
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name);
...
end
Based on the examples in the MATLAB documentation:
Accepted Answer
madhan ravi
on 11 Oct 2018
To process sequence of files:
2 Comments
Kevin Chng
on 11 Oct 2018
I just to explain it further for MOMIL IJAZ
It is always better to specify what kind of files you want to load in the folder.
AllFiles=dir('*.mat');
which it does not done in original script.
More Answers (0)
See Also
Categories
Find more on File Operations 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!