How do I open files from different subfolders?

Hi All,
A part of my script is openning files to read. My code works as long as files are in the same directory as my m file. My files are stored in several different subfolders. Is there any function that would tell matlab to search for files in all subfolders or do I have to define directory every time? All file names that I want to open are different.
Thank you very much for your help!
Jo

Réponses (2)

If you know the folder names you can use fullfile.
fullFileName = fullfile(folder, 'foo.txt');
If you want the user to select the file, you can do:
% Have user browse for a file, from a specified "starting folder."
% For convenience in browsing, set a starting folder from which to browse.
startingFolder = pwd; % or 'C:\wherever';
if ~isfolder(startingFolder)
% If that folder doesn't exist, just start in the current folder.
startingFolder = pwd;
end
% Get the name of the file that the user wants to use.
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uigetfile(defaultFileName, 'Select a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
Rik
Rik le 8 Juil 2022

0 votes

There is presumably some structure or pattern to your files. You should use the dir function and make use of that pattern. The dir function will return a struct array you can use to loop through all files.
You can use a wildcard * to match partial or full file or folder names, and you can even use to indicate a recursive search.

Catégories

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

Question posée :

le 8 Juil 2022

Réponse apportée :

Rik
le 8 Juil 2022

Community Treasure Hunt

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

Start Hunting!

Translated by