As an example, let's say I have three subfolders in 'My_Dir'
called 'A'
(containing 'a1.txt'
and 'a2.txt'
), 'B'
(containing 'b1.txt'
), and 'C'
(containing 'c1.txt'
, 'c2.txt'
, and 'c3.txt'
). This will illustrate how to handle a case with different numbers of files in each subfolder...
For MATLAB versions R2016b and later, the dir
function supports recursive searching, allowing us to collect a list of files like so:
dirData = dir('My_Dir\*\*.*'); % Get structure of folder contents
dirData = dirData(~[dirData.isdir]); % Omit folders (keep only files)
fileList = fullfile({dirData.folder}.', {dirData.name}.'); % Get full file paths
fileList =
6×1 cell array
'...\My_Dir\A\a1.txt'
'...\My_Dir\A\a2.txt'
'...\My_Dir\B\b1.txt'
'...\My_Dir\C\c1.txt'
'...\My_Dir\C\c2.txt'
'...\My_Dir\C\c3.txt'
As an alternative, in particular for earlier versions, this can be done using a utility I posted to the MathWorks File Exchange: dirPlus
. It can be used as follows:
dirData = dirPlus('My_Dir', 'Struct', true, 'Depth', 1);
fileList = fullfile({dirData.folder}.', {dirData.name}.');
Now we can format fileList
in the way you specified above. First we can use unique
to get a list of unique subfolders and an index. That index can then be used with mat2cell
and diff
to break fileList
up by subfolder into a second level of cell array encapsulation:
[dirList, index] = unique({dirData.folder}.');
outData = [dirList mat2cell(fileList, diff([index; numel(fileList)+1]))]
outData =
3×2 cell array
'...\My_Dir\A' {2×1 cell}
'...\My_Dir\B' {1×1 cell}
'...\My_Dir\C' {3×1 cell}