You can simply use strfind
to find the extension of interest within your filename, put that inside an anonymous function, and use cellfun
to let this anonymous function work on each of your cell array elements.
Please have a look at the following code snippet:
% Files cell array
files = {
'text1.txt',
'text2.txt',
'image1.png',
'image2.jpg',
'audio1.mp3',
'audio2.mp3'
}
% Extension of interest
ext = 'txt';
% Use strfind operation in cellfun
temp = cellfun(@(x) ~isempty(strfind(x, ['.' ext])), files, 'UniformOutput', false)
% Combine outputs, and find proper indices
idx = find([temp{:}])
% Get files with extension of interest
filesExt = files(idx)
% Get files with extension of interest as one-liner
% (for the Octave users, where the syntactic sugar for {:} is available)
filesExt = files(find([cellfun(@(x) ~isempty(strfind(x, ['.' ext])), files, 'UniformOutput', false){:}]))
And, this is the output:
files =
{
[1,1] = text1.txt
[2,1] = text2.txt
[3,1] = image1.png
[4,1] = image2.jpg
[5,1] = audio1.mp3
[6,1] = audio2.mp3
}
temp =
{
[1,1] = 1
[2,1] = 1
[3,1] = 0
[4,1] = 0
[5,1] = 0
[6,1] = 0
}
idx =
1 2
filesExt =
{
[1,1] = text1.txt
[2,1] = text2.txt
}
filesExt =
{
[1,1] = text1.txt
[2,1] = text2.txt
}
Since I'm currently on Octave, I can't guarantee the one-liner to work on MATLAB. Maybe, someone can please confirm. Anyway, the step-by-step solution should work as intended.
Hope that helps!
EDIT: As Wolfie points out in his answer, "double file extensions" like x.txt.png
might cause trouble using this approach.