要以编程方式遍历文件,请使用dir 命令获取目录中所有文件的列表。 Documentation for dir
例如,可以通过以下命令获取当前目录下的文件列表:
list = dir
list =
4×1 struct array with fields:
name
folder
date
bytes
isdir
datenum
在这种情况下,我在当前目录中有 2 个文件,另外还有 2 个 inode('.' 和 '..')。这些都存储在一个名为list 的结构数组中。可以通过命令查看文件列表:
{list.name}
ans =
1×4 cell array
{'.'} {'..'} {'fileA.m'} {'fileB.m'}
可以使用sprintf() 以编程方式生成文件名。 Documentation for sprintf
for i = 1:10
sprintf("sample%d.png", i)
end
ans =
"sample1.png"
ans =
"sample2.png"
ans =
"sample3.png"
...
将两者结合在一起,您可以使用如下代码遍历列表中的所有文件:
list = dir; % Get files in current directory
fileList = {list.name}; % Store filenames in a cell array
fileList(1:2) = []; % Delete the inodes '.' and '..'
for i = 1:length(fileList)
% Get current filename, use curly brackets to extract string from cell array
currentFile = fileList{i};
% Use sprintf() to automatically generate filenames
saveName = sprintf("sample%d.png", i);
% Your code goes here
[y,Fs] = audioread(currentFile);
spectrogram(y,'yaxis')
saveas(gcf,saveName)
end
如果移动到目标文件的目录不方便,可以给dir命令一个目标目录:list = dir('C:/TargetDirectory/')。这将为您提供该目录中的文件列表,但请注意,您必须将该目标目录添加到 MATLAB 路径中,或者在加载时将其显式添加到目标文件名中。例如:
% Directory path, use double quotes, not single quotes
targetDirectory = "C:/TargetDirectory/";
currentFile = fileList{i};
currentFile = targetDirectory + currentFile; % Append path to file
% Do stuff
load(currentFile)