I want to run a loop that will access files from multiple folders
I used dir to retrieve the names of the folders and I want to be able to feed the names into fopen.
ex:
folder = dir('W:\Examples')
#_of_folders = numel(folder)
for i=1:#_of_folders
fid = fopen('W:\Examples\folder([i])')
...
end
How can I enter that variable into fopen? Is there a better way of achieving this?
I did take a look at this thread, but I am still having trouble.
Thank you

1 commentaire

Stephen23
Stephen23 le 11 Sep 2014
Don't forget to use fclose after you have read the file data! This will save a lot of bug-finding nightmares later...

Connectez-vous pour commenter.

 Réponse acceptée

Iain
Iain le 11 Sep 2014

0 votes

init = 'W:\Examples';
folder = dir(init)
for i = 1:numel(folder)
% do something with folder(i) to figure out if it's a file you want to open, or a folder you want to search, and if so:
filename = [init '\' folder(i).name]; % or filename = [init '\' folder(i).name '\' folder(i).name '.abc']; if you know that the folders contain files with the same name as the folder and a fixed extension...
% do something with filename
fid = fopen(filename,'r');
end

Plus de réponses (1)

Ken Atwell
Ken Atwell le 11 Sep 2014

1 vote

You can use fullfile as a convenient way to create a full path from parts. 'folder' as returned by dir will be an array of structs -- you are interested in the 'name' field.
(Note you can't use "#" as part of a MATLAB variable name, so I've use "num_files" instead)
folder = dir('W:\Examples')
num_files = numel(folder)
for i=1:num_files
fid = fopen(fullfile('W:\Examples', folder(i).name))
...
end

3 commentaires

Andrew
Andrew le 11 Sep 2014
Modifié(e) : Andrew le 11 Sep 2014
Thank you for your answer.
An addition question, I need access to files in those folders.
Initially i had:
fid = fopen('W:\Examples\foldername\folder\file')
In the line above, I am retrieving the foldername (through dir)as mentioned in my original question. The folder in those " foldernames" and the file in that are the same for each on of those " foldernames".
How can I write this?
I'm not quite following, but you can pass an arbitrary number of pieces to fullpath:
fid = fopen(fullpath('W:\Examples', folder(i).name, 'folder', 'file'))
Andrew
Andrew le 23 Sep 2014
Thank you, this worked perfectly

Connectez-vous pour commenter.

Catégories

En savoir plus sur File Operations dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by