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

6 vues (au cours des 30 derniers jours)
MOMIL IJAZ
MOMIL IJAZ le 11 Oct 2018
Commenté : MOMIL IJAZ le 11 Oct 2018
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 commentaires
Stephen23
Stephen23 le 11 Oct 2018
Modifié(e) : Stephen23 le 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:
MOMIL IJAZ
MOMIL IJAZ le 11 Oct 2018
Great Updated!!

Connectez-vous pour commenter.

Réponse acceptée

madhan ravi
madhan ravi le 11 Oct 2018
  2 commentaires
Kevin Chng
Kevin Chng le 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.
MOMIL IJAZ
MOMIL IJAZ le 11 Oct 2018
Got it done!! Thank u

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur File Operations dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by