0

我正在将一些文件分配给 MATLAB 中的变量。我有点懒惰,并试图展示一些解决问题的方法,所以我尝试编写一个函数来做到这一点。函数体:

i=0
for i=0:8
    eval(sprintf('C%d=wavread([''C'' num2str(i)]);', i));
    eval(sprintf('Cs%d=wavread([''Cs'' num2str(i)]);', i));
    eval(sprintf('D%d=wavread([''D'' num2str(i)]);', i));
    eval(sprintf('Ef%d=wavread([''Ef'' num2str(i)]);', i));
    eval(sprintf('E%d=wavread([''E'' num2str(i)]);', i));
    eval(sprintf('F%d=wavread([''F'' num2str(i)]);', i));
    eval(sprintf('Fs%d=wavread([''Fs'' num2str(i)]);', i));
    eval(sprintf('G%d=wavread([''G'' num2str(i)]);', i));
    eval(sprintf('Af%d=wavread([''Af'' num2str(i)]);', i));
    eval(sprintf('A%d=wavread([''A'' num2str(i)]);', i));
    eval(sprintf('Bf%d=wavread([''Bf'' num2str(i)]);', i));
    eval(sprintf('B%d=wavread([''B'' num2str(i)]);', i));
    i=i+1
end

当我只为 i 赋值并在循环中运行代码时,一切都很糟糕,但是当我实际将它作为循环运行时,它只会运行完成而不返回任何变量。

任何想法为什么?

谢谢大家!还弄清楚了为什么我的函数没有返回任何东西!愚蠢的错误:)

4

2 回答 2

1

I believe this is because eval generates its own workspace, so whilst the variables are being created, they are then lost at the end of the eval call, a bit like the way variables created inside a function are lost when it returns. I suggest you do this the 'proper' way and use cell arrays instead:

i = 0; % Note: uneccessary line!
for i = 0:8
    C{i + 1} = wavread(['C' num2str(i)]);
    Cs{i + 1} = wavread(['Cs' num2str(i)]);
    D{i + 1} = wavread(['D' num2str(i)]);
    Ef{i + 1} = wavread(['Ef' num2str(i)]);
    E{i + 1} = wavread(['E' num2str(i)]);
    F{i + 1} = wavread(['F' num2str(i)]);
    Fs{i + 1} = wavread(['Fs' num2str(i)]);
    G{i + 1} = wavread(['G' num2str(i)]);
    Af{i + 1} = wavread(['Af' num2str(i)]);
    A{i + 1} = wavread(['A' num2str(i)]);
    Bf{i + 1} = wavread(['Bf' num2str(i)]);
    B{i + 1} = wavread(['B' num2str(i)]);
    i = i+1;  % Note: uneccessary line!
end

EDIT: Ignore what I said about eval, see Dan's comment below. Nonetheless, a cell array is the appropriate way to tackle this.

于 2013-04-27T21:51:28.913 回答
0

如果您的代码是您所说的函数的主体,那么生成的代码eval将作用于该函数。一旦函数返回,变量就会被释放。jazzbassrob 发布的代码如果在函数中也将不起作用,但这绝对是正确的方法。只需将其设为脚本而不是函数即可。或者更好的是,让函数返回元胞数组:

function [C, Cs, ...] = readWavs()
    for ii = 0:8
        C{ii} = wavread(['C' num2str(ii)]);
        ....
        ii = ii + 1 %NB this line makes no sense! i will increment by 1 anyway because of the for loop. If you want to increment by 2 then you should change the loop to for ii = 0:2:8
    end
end

或单元格数组的结构:

function wavStruct = readWavs()
    for ii = 0:8
        wavStruct{ii}.C = wavread(['C' num2str(ii)]);
        ...
    end
end

另外最好不要在 matlab 中使用iorj作为变量名,因为它们是为 保留的sqrt(-1),因此我使用了ii

于 2013-04-27T22:43:32.460 回答