How can I process all the files with ".xyz" extension in a folder? The basic idea is that I want a list of file names and then a for loop to load each file.
Asked
Active
Viewed 4.5k times
4 Answers
27
As others have already mentioned, you should use the DIR function to list files in a directory.
If you are still looking, here is an example to show how to use the function:
dirName = 'C:\path\to\folder'; %# folder path
files = dir( fullfile(dirName,'*.xyz') ); %# list all *.xyz files
files = {files.name}'; %'# file names
data = cell(numel(files),1); %# store file contents
for i=1:numel(files)
fname = fullfile(dirName,files{i}); %# full path to file
data{i} = myLoadFunction(fname); %# load file
end
Of course, you would have to supply the function that actually reads and parses the XYZ files.

Amro
- 123,847
- 25
- 243
- 454
18
Use dir()
to obtain a list of filenames. You can specify wildcards.

Oliver Charlesworth
- 267,707
- 33
- 569
- 680
4
You could use
fileName=ls('*xyz')
.
fileName variable will have the list of all the filenames which you can use in the for loop

Kiran
- 8,034
- 36
- 110
- 176
-
2Be careful, [ls](http://www.mathworks.de/help/techdoc/ref/ls.html) returns a different syntax on Windows or Unix! – Jonas Heidelberg Sep 02 '11 at 21:40
-
This will pad space to the filenames and make them equal length, which is not good. – LWZ Jun 04 '13 at 02:33
-
1@LWZ: unnecessary space can be remove with the standard strtrim function. – Mostafa Mahdieh May 20 '15 at 08:29
0
Here is my answer:
dirName = 'E:\My Matlab\5';
[sub,fls] = subdir(dirName);
D = [];
j = 1;
for i=1:length(sub),
files{i} = dir( fullfile(sub{i},'*.xyz') );
if length(files{i})==1
D(j) = i;
files_s{j} = sub{i};
j=j+1;
end
end
varaible files_s
returns the desire paths that contain those specific data types!
The subdir function can be found at: http://www.mathworks.com/matlabcentral/fileexchange/1492-subdir--new-

Vahab Yousofzadeh
- 11
- 2