【发布时间】:2014-11-12 15:00:51
【问题描述】:
我在 Matlab 中的“case”语句之间共享变量时遇到问题。 我正在编写一个延迟音频文件的梳状滤波器。
这是完整的代码:
%Initial valuses of RT and Tc
Tc = 0.02;
RT = 0.5;
fs = 44100;
Ts = 1/fs;
M = Tc/Ts;
g = 0.001^(Tc/RT);
N = fs*RT;
f = linspace(0,fs*(1-1/N),N);
t = linspace(0,length(x)/fs,length(x));
global q
q = 1;
%Number of rows of graphs
G1 = 3;
%Number of columbs of graphs
G2 = 1;
%Do this untill the user hits q
while q == 1
%Options presented to the user
input_label = input('Enter command (o, p_p, p_up, pro, s, RT, Tc, plot, quit): ','s');
switch input_label
case 'o'
%Open wav file
[x,fs] = wavread('Audio_1');
disp('**Audio File Opened**');
%If user wants to change reverberation time
case 'RT'
disp('Change RT to:');
RT_input = input('','s');
fprintf('**RT changed to:%s**\n',RT_input)
%If user wantes to change delay time
case 'Tc'
disp('Change Tc to:');
Tc_input= input('','s');
fprintf('**Tc changed to:%s**\n',Tc_input)
%PROBLEM%
%Can change RT and Tc in this script but not in the running program
%Doesnt seem to be able to access RT and Tc from the above RT and Tc 'cases'
case 'pro'
%print statments show that the values RT and Tc HAVE been changed when 'pro' is run
RT = RT_input;
%fprintf('**RT:%s**\n',RT)
Tc = Tc_input;
%fprintf('**Tc:%s**\n',Tc)
%Comb filter audio
b =[zeros(1, M) 1];
a =[1 zeros(1, M-1) -g];
H = (b/a); %Not necessary
%Filter function uses H(b/a) withing function
y = filter(b, a, x);
%Calculate impulse responce
[imp,f] = impz(b,a);
%Calculates the frequency responce using a & b
fr = freqz(b,a,N);
case 'plot'
%Plots the input wave
subplot(G1,G2,1);
plot(t,x);
title('Input');
%Plots the output wave
subplot(G1,G2,2);
plot(t,y,'r');
title('Output');
%Plots the impulse responce of output wave
subplot(G1,G2,3);
plot(f,imp);
title('Impulse Response');
case 'quit'
disp('**Program Terminated**')
q = 0;
return
otherwise
disp('Unrecognised input, please try again...')
end
end
下面是程序的运行方式:
用户:o
程序打开音频文件
用户:RT
然后用户输入 RT 的值
用户:Tc
然后用户输入 Tc 的值
用户:专业人士
相应处理音频文件
用户:情节
原始音频文件被绘制 绘制处理后的音频文件 绘制频率响应
然后用户应该能够更改 RT 和 Tc 的值,使用与上述相同的步骤重新处理音频并重新绘制。
值 RT 和 Tc 用于计算 g、N 和 M(在代码顶部定义)。
当我在脚本运行并输入新值时调用 RT 和 Tc 案例时,就好像没有将新值分配给 RT 和 Tc,这意味着图表不会按应有的变化。
但是,如果我在运行脚本之前更改 RT 和 Tc 的值,它会相应地更改图形。这意味着变量不会跨案例共享。
为什么?
%EDIT:“pro”案例中的两条 fprintf 行导致 matlab 中断(无法重新运行程序) 如果我能找出原因,那就太好了。
【问题讨论】:
-
你能分享足够的代码来重现这个问题吗?您是否将
RT_input作为输出变量传递并在再次调用时将其传递给函数(或您发布的任何内容)? -
我已经彻底编辑了我的问题,希望这会让事情更清楚
-
为什么将输入作为字符串?例如
RT_input = input('','s'); -
这是一个好点,但根据 matlab,它必须是一个 's'。然后我如何将其更改为双精度?
-
str2num,我不确定's'是否必要; first example.
标签: matlab variables switch-statement case