2017-08-26 65 views
2

我在写一个程序来具有零均值和单位方差 添加的高斯噪声的信号,而不在八度使用内置功能:变量未定义,尽管内部被定义if语句

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 

我怎样才能解决这个问题?

+1

如果您有错误消息引用行号,请始终在您的发布代码中标记行或在源代码中提及其对应的行。 – Andy

回答

3

你认为real(x3)的逻辑值是什么?这就是你要求的。这就像要求如果苹果,做...什么是苹果?由于这不是二进制值,也不是imag(x3),因此您的if语句将永远不会执行。目前尚不清楚你想要这个if声明做什么,但有几个逻辑操作可以进行如下:

real(x3) > imag(x3) 
real(x3) == imag(x3) % You might want to do this within tolerance 

正如Andy提到你很可能会寻找是否是真实的还是复杂,从而修改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等,所以我建议你看一下在适当的基本tutolrial用于MATLAB/Octave编程。