DIR multiple file extensions

Hi, is there a simpler and shorter way for writing this code?
The code is working fine so I assume I'm writing it correctly, just that if there are more extensions to be added, it will be long and repetitive.
extensions = [...
dir(fullfile(folder,'*.txt'));
dir(fullfile(folder, '*.py'));
dir(fullfile(folder, '*.mp3'));
dir(fullfile(folder, '*.exe'));
dir(fullfile(folder,'*.jpg'));
];

 Accepted Answer

You can put those dir() calls in cellfun:
ext = {'*.txt','*.py','*.mp3','*.exe','*.jpg'};
extensions = cellfun(@(x)dir(fullfile(folder,x)),ext,'UniformOutput',false);
extensions = vertcat(extensions{:});
Then when you need to add more extensions, just include them in the 'ext' variable.

4 Comments

Lisa Loh
Lisa Loh on 5 Feb 2023
Edited: Lisa Loh on 5 Feb 2023
Thank you for answering!
Your code works fine.
Does @(x) means anonymous cell function? I'm confused about the usage of x in the 2nd line.
I've read up about vertcat, based on my understanding is it to concatenate the extension files instead of extensions?
Voss
Voss on 5 Feb 2023
Edited: Voss on 5 Feb 2023
You're welcome!
I placed all the character arrays indicating the file types you want to check for ('*.txt', '*.py', etc.) into the cell array 'ext'.
Then cellfun is used to apply a function to each element of that cell array. In this case the function is the anonymous function @(x)dir(fullfile(folder,x)). Each file type to check for will be substituted in for x when cellfun runs, so cellfun is essentially doing the same thing as the sequence of dir() calls you had in your original code.
In general, the result from a dir() call is a struct column vector (i.e., a struct array of size N-by-1 for some N), so I use 'UniformOutput',false so that cellfun returns a cell array containing all those struct column vectors.
Then I vertcat() the struct arrays together at the end into a single struct column vector containing the results for all the file types. This is the same operation your original code did to combine the results of all the dir() calls.
(Without 'UniformOutput',false, cellfun would try to combine the results from the dir() calls into a single struct array under the assumption that each dir() call returns a scalar struct, and this would fail and throw an error if any of the dir() calls returns a non-scalar struct, i.e., if not exactly one file of any given type was found.)
Thank you very much for the deep explanation!
You're welcome!

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2022b

Asked:

on 5 Feb 2023

Commented:

on 6 Feb 2023

Community Treasure Hunt

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

Start Hunting!