如何从 MATLAB 上的元胞数组访问特定文件扩展名的文件

How to access files of a specific file extension from a cell array on MATLAB

我正在尝试访问我在 MATLAB 上创建的元胞数组中具有特定文件扩展名的所有文件,但我不确定如何执行此操作。此外,我需要能够将其设为可变输入。即当我调用我的函数时,我可以输入不同的文件扩展名来访问与输入的文件扩展名对应的不同文件。

任何帮助将不胜感激!!

您可以简单地使用 strfind to find the extension of interest within your filename, put that inside an anonymous function, and use cellfun 让这个匿名函数作用于您的每个元胞数组元素。

请查看以下代码片段:

% 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){:}]))

而且,这是输出:

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
}

由于我目前使用的是 Octave,因此我无法保证单行代码可以在 MATLAB 上运行。也许,有人可以确认一下。无论如何,分步解决方案应该会按预期工作。

希望对您有所帮助!


编辑: 一样,"double file extensions" 与 x.txt.png 一样可能会在使用此方法时出现问题。

使用 filepartsregexp 最简单...

% mock data
files = {'a.txt', 'b.png', 'c.txt', 'd.txt.pdf'}; % note d is actually a .pdf file
target = '.txt';

fileparts的第三个输出是文件扩展名,所以

% option 1 - fileparts
[~,~,ext] = cellfun( @fileparts, files, 'uni', 0 );
files = files( strcmp( target, ext ) );

regexp 选项比 strfind 更可靠,因为您可以确保扩展名位于字符串的末尾

% option 2 - regexp ('$' to specify end of string)
files = files( ~cellfun( @isempty, regexp( files, [target, '$'], 'once' ) ) );