How do I open files from different subfolders?

35 views (last 30 days)
JLema
JLema on 8 Jul 2022
Answered: Rik on 8 Jul 2022
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

Answers (2)

Image Analyst
Image Analyst on 8 Jul 2022
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 on 8 Jul 2022
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.

Categories

Find more on File Operations in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!