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

3 Ansichten (letzte 30 Tage)
MOMIL IJAZ
MOMIL IJAZ am 11 Okt. 2018
Kommentiert: MOMIL IJAZ am 11 Okt. 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 Kommentare
Stephen23
Stephen23 am 11 Okt. 2018
Bearbeitet: Stephen23 am 11 Okt. 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 am 11 Okt. 2018
Great Updated!!

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

madhan ravi
madhan ravi am 11 Okt. 2018
  2 Kommentare
Kevin Chng
Kevin Chng am 11 Okt. 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 am 11 Okt. 2018
Got it done!! Thank u

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu File Operations finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by