【问题标题】:How can I automatically let Matlab input the file in sequence?如何让Matlab自动按顺序输入文件?
【发布时间】:2020-07-20 23:15:59
【问题描述】:

如何让Matlab自动输入文件而不是自己一个一个输入?

我的意思是,我想输入Sample 1.wav,然后输出Sample 1.png,然后 输入Sample 2.wav再输出Sample 2.png再输入Sample 3.wav再输出Sample 3.png

我不想自己输入 1、2、3,而是让 matlab 从 1 to 1,000 自行运行

[y,Fs] = audioread('sample1.wav');
spectrogram(y,'yaxis')
saveas(gcf,'sample1.png')

然后

[y,Fs] = audioread('sample2.wav');
spectrogram(y,'yaxis')
saveas(gcf,'sample2.png')

然后

[y,Fs] = audioread('sample3.wav');
spectrogram(y,'yaxis')
saveas(gcf,'sample3.png')

【问题讨论】:

  • 可以尝试迭代

标签: matlab iteration


【解决方案1】:

要以编程方式遍历文件,请使用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)

【讨论】:

    猜你喜欢
    • 2015-01-24
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    相关资源
    最近更新 更多