变量未定义,尽管在 if 语句中定义
Variable is undefined, despite being defined inside an if-statement
我正在编写一个程序来添加具有零均值和单位方差的高斯噪声
在不使用八度音阶中的内置函数的情况下发送信号:
t=0:0.001:2;
x1=sin(2*pi*10*t);
x2=sin(2*pi*5*t)+sin(2*pi*50*t);
x3=x1+x2;
d=0;
L=length(x3);
for i = 1:L
d+=(abs(x3(i))^2);
endfor
Es=(1/L)*d;
SNR=20;
for i = 1:L
if (real(x3))
noise=sqrt(Es/SNR)*randn(1,L);
elseif (imag(x3))
noise=sqrt(Es/(2*SNR))*(randn(1,L)+(i*randn(1,L)));
endif
endfor
x4=x3+noise;
fs=1000;
N=1024;
y=fftshift(fft(x4,N));
fval=(fs/N)*(-N/2:N/2-1);
subplot(2,1,1);
plot(t,x4,'g');
xlabel('Time');
ylabel('Amplitude');
title('x4(t)');
subplot(2,1,2);
plot(fval,y,'b');
xlabel('Frequency');
ylabel('Amplitude');
title('X4(f):Frequency Response');
figure
subplot(2,1,1);
plot(fval,abs(y),'r');
xlabel('Frequency');
ylabel('Amplitude');
title('Amplitude Response');
subplot(2,1,2);
plot(fval,angle(y),'m');
xlabel('Frequency');
ylabel('Amplitude');
title('Phase Response');
但我无法解决不断出现的错误:
error: 'noise' undefined near line 27 column 7
如何解决这个错误?
您认为 real(x3)
的逻辑值是多少?那就是你要问的。这就像问 如果是 apple,做... 什么是 apple?由于这不是二进制值,imag(x3)
也不是,因此您的 if
语句将永远不会执行。不清楚你想要这个 if
语句做什么,但是可以进行一些逻辑操作,如下所示:
real(x3) > imag(x3)
real(x3) == imag(x3) % You might want to do this within tolerance
等等
正如 Andy 提到的,您很可能正在寻找 x3
是实数还是复数,因此像这样修改您的 if
语句:
if isreal(x3)
noise=sqrt(Es/SNR)*randn(1,L);
else
noise=sqrt(Es/(2*SNR))*(randn(1,L)+(i*randn(1,L)));
endif
不同之处在于,如果x3 = 4
, real(x3) = 4
, 这不符合逻辑,而 isreal(x3) = true
.
代码还有很多问题,比如每次循环迭代都用一个完整的新数组覆盖 noise
变量,将循环索引 i
误认为是复杂变量 i
等,所以我建议您也查看 MATLAB/Octave 编程的适当基本教程。
我正在编写一个程序来添加具有零均值和单位方差的高斯噪声 在不使用八度音阶中的内置函数的情况下发送信号:
t=0:0.001:2;
x1=sin(2*pi*10*t);
x2=sin(2*pi*5*t)+sin(2*pi*50*t);
x3=x1+x2;
d=0;
L=length(x3);
for i = 1:L
d+=(abs(x3(i))^2);
endfor
Es=(1/L)*d;
SNR=20;
for i = 1:L
if (real(x3))
noise=sqrt(Es/SNR)*randn(1,L);
elseif (imag(x3))
noise=sqrt(Es/(2*SNR))*(randn(1,L)+(i*randn(1,L)));
endif
endfor
x4=x3+noise;
fs=1000;
N=1024;
y=fftshift(fft(x4,N));
fval=(fs/N)*(-N/2:N/2-1);
subplot(2,1,1);
plot(t,x4,'g');
xlabel('Time');
ylabel('Amplitude');
title('x4(t)');
subplot(2,1,2);
plot(fval,y,'b');
xlabel('Frequency');
ylabel('Amplitude');
title('X4(f):Frequency Response');
figure
subplot(2,1,1);
plot(fval,abs(y),'r');
xlabel('Frequency');
ylabel('Amplitude');
title('Amplitude Response');
subplot(2,1,2);
plot(fval,angle(y),'m');
xlabel('Frequency');
ylabel('Amplitude');
title('Phase Response');
但我无法解决不断出现的错误:
error: 'noise' undefined near line 27 column 7
如何解决这个错误?
您认为 real(x3)
的逻辑值是多少?那就是你要问的。这就像问 如果是 apple,做... 什么是 apple?由于这不是二进制值,imag(x3)
也不是,因此您的 if
语句将永远不会执行。不清楚你想要这个 if
语句做什么,但是可以进行一些逻辑操作,如下所示:
real(x3) > imag(x3)
real(x3) == imag(x3) % You might want to do this within tolerance
等等
正如 Andy 提到的,您很可能正在寻找 x3
是实数还是复数,因此像这样修改您的 if
语句:
if isreal(x3)
noise=sqrt(Es/SNR)*randn(1,L);
else
noise=sqrt(Es/(2*SNR))*(randn(1,L)+(i*randn(1,L)));
endif
不同之处在于,如果x3 = 4
, real(x3) = 4
, 这不符合逻辑,而 isreal(x3) = true
.
代码还有很多问题,比如每次循环迭代都用一个完整的新数组覆盖 noise
变量,将循环索引 i
误认为是复杂变量 i
等,所以我建议您也查看 MATLAB/Octave 编程的适当基本教程。