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

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 comentarios

Stephen23
Stephen23 el 11 de Oct. de 2018
Editada: Stephen23 el 11 de Oct. de 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 el 11 de Oct. de 2018
Great Updated!!

Iniciar sesión para comentar.

 Respuesta aceptada

madhan ravi
madhan ravi el 11 de Oct. de 2018

2 comentarios

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 el 11 de Oct. de 2018
Got it done!! Thank u

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 11 de Oct. de 2018

Comentada:

el 11 de Oct. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by