【问题标题】:Matlab: read multiple filesMatlab:读取多个文件
【发布时间】:2018-09-17 11:13:43
【问题描述】:

我的 matlab 脚本读取了一个文件夹中包含的几个 wav 文件。 每个读取信号都保存在单元格“mat”中,每个信号都保存在数组中。例如, 我有 3 个 wav 文件,我读取了这些文件,这些信号保存在数组“a、b 和 c”中。

我想应用另一个函数,该函数将每个信号(a、b 和 c)和对应的名称作为输入 文件。

dirMask = '\myfolder\*.wav';  
fileRoot = fileparts(dirMask);
Files=dir(dirMask);

N = natsortfiles({Files.name});
C = cell(size(N));
D = cell(size(N));

for k = 1:numel(N)
    str =fullfile(fileRoot, Files(k).name);
    [C{k},D{k}] = audioread(str);

    mat = [C(:)];
    fs = [D(:)];

    a=mat{1};
    b=mat{2};
    c=mat{3};

     myfunction(a,Files(1).name);
     myfunction(b,Files(2).name);
     myfunction(c,Files(3).name);

end

我的脚本不起作用,因为 myfunction 只考虑文件夹中包含的最后一个 Wav 文件,尽管 数组 a、b 和 c 包含三个不同的信号。

如果我只读取一个 wav 文件,脚本运行良好。 for 循环有什么问题?

【问题讨论】:

  • 在您的 for 循环中,k 是文件号。当你分配到ab abd c 和调用myfunction 时,你根本不使用k。您确定要将那部分放在循环中吗?

标签: matlab cell wav


【解决方案1】:

就像 Cris 注意到的那样,您在构建 for 循环的方式上存在一些问题。您正在尝试使用“b”和“c”,甚至在他们获得任何数据之前(通过循环的第二次和第三次)。假设您有理由按照您的方式构建程序(我会重写循环,以便您不使用“a”、“b”或“c”。只需发送“myfunction”的适当索引mat') 以下应该可以工作:

dirMask = '\myfolder\*.wav';  
fileRoot = fileparts(dirMask);
Files=dir(dirMask);

N = natsortfiles({Files.name});
C = cell(size(N));
D = cell(size(N));

a = {};
b = {};
c = {};

for k = 1:numel(N)
    str =fullfile(fileRoot, Files(k).name);
    [C{k},D{k}] = audioread(str);

    mat = [C(:)];
    fs = [D(:)];

    a=mat{1};
    b=mat{2};
    c=mat{3};
end

myfunction(a,Files(1).name);
myfunction(b,Files(2).name);
myfunction(c,Files(3).name);

编辑

我想花点时间澄清一下我说我不会使用 a、b 或 c 变量的意思。请注意,我可能会在您所问的内容中遗漏一些东西,所以我可能会解释您已经知道的事情。

在这样的特定场景中,可以准确地说明您将使用多少个变量。在您的情况下,您知道您要处理的正是 3 个音频文件。因此,变量 a、b 和 c 可以出来。太好了,但是如果您必须放入另一个音频文件怎么办?现在您需要返回并添加一个“d”变量和另一个对“myfunction”的调用。有一种更好的方法,不仅可以降低复杂性,还可以扩展程序的功能。见以下代码:

%same as your code
dirMask = '\myfolder\*.wav';
fileRoot = fileparts(dirMask);
Files = dir(dirMask);

%slight variable name change, k->idx, slightly more meaningful. 
%also removed N, simplifying things a little.
for idx = 1:numel(Files)
    %meaningful variable name change str -> filepath.
    filepath = fullfile(fileRoot, Files(idx).name);

    %It was unclear if you were actually using the Fs component returned
    %from the 'audioread' call. I wanted to make sure that we kept access
    %to that data. Note that we have removed 'mat' and 'fs'. We can hold
    %all of that data inside one variable, 'audio', which simplifies the 
    %program.
    [audio{idx}.('data'), audio{idx}.('rate')] = audioread(filepath);

    %this function call sends exactly the same data that your version did
    %but note that we have to unpack it a little by adding the .('data').
    myfunction(audio{idx}.('data'), Files(idx).name);
end

【讨论】:

  • 如何进行循环,不要使用 a、b 和 c?我总是出错
  • @user3582433 看到我的编辑,我希望我能把事情弄清楚一点。
猜你喜欢
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多