How to run a for loop with a string as loop index?

6 views (last 30 days)
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
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:

Sign in to comment.

Accepted Answer

madhan ravi
madhan ravi on 11 Oct 2018
  2 Comments
Kevin Chng
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.

Sign in to comment.

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!