用matlab语言产生一个正弦信号,进行频谱分析和自相关分析,求教~~~~~谢谢啊
下面matlab程序,按照你的要求编写的。
fs=100;N=200;
lag=100;
%randn('state',0); %设置产生随机数的初始状态(噪声)
n=0:N-1;t=n/fs;
x1=sin(2*pi*10*t)+2*sin(2*pi*15*t)
y=fft(x1,N); %计算频谱
mag=abs(y);
f=n*fs/N;
figure(1)
subplot(2,2,1),plot(t,x1);
title('原始信号'),xlabel('时间/s');
subplot(2,2,2),plot(f(1:N/2),mag(1:N/2)*2/N);
title('频谱图'),xlabel('频率/Hz');
[c,lags]=xcorr(x1,lag,'unbiased'); % 自相关
subplot(2,2,3),plot(lags/fs,c);
title('自相关信号'),xlabel('时间/s');
m=length(c)-1;
z=fft(c,m);
mag_z=abs(z);
ff=(0:m-1)*fs/m;
subplot(2,2,4),plot(ff(1:m/2),mag_z(1:m/2)*2/m);
title('自相关频谱'),xlabel('频率/Hz');
figure(2)
[c1,lags1]=xcorr(x1,randn(1,length(t)),lag,'unbiased');
m1=length(c1)-1;
z1=fft(c1,m1);
mag_z1=abs(z1);
ff1=(0:m1-1)*fs/m1;
subplot(2,1,1),plot(lags1/fs,c1);
title('互相关信号'),xlabel('时间/s');
subplot(2,1,2),plot(ff1(1:m1/2),mag_z1(1:m1/2)*2/m1);
title('互相关频谱'),xlabel('频率/Hz');
% truncation is needed to achieve the requirement
%--------------------------------------------------------------------------
% (1) Compute number of data points and sampling time interval
%--------------------------------------------------------------------------
ntime=max(size(t));
dt=(t(1,ntime)-t(1,1))/(ntime-1);
%--------------------------------------------------------------------------
% (2) Truncate the data points of y
%--------------------------------------------------------------------------
% Extract data points at the power of 2. Truncate extra data points
% so that the final number of data points is in the power of two and
% also as close as possible to the given number of data points
N=fix(log10(ntime)/log10(2))
%--------------------------------------------------------------------------
% (3) Calculate FFT
%--------------------------------------------------------------------------
% Calculate FFT of the time domain data and
% take absolute values of the result
yfft=fft(y(1:2^N,:));
yfft=abs(yfft(1:2^N/2,:))*dt;
%--------------------------------------------------------------------------
% (4) Calculate frequency vector
%--------------------------------------------------------------------------
% Set up the frequency scale from the given sampling interval.
% Apply the Nyquist criterion to establish the maximum frequency
freq0=0;
freqf= (1/dt)/2; % Maximum or final frequency value
df=freqf/(2^N/2); % Frequency interval
freq=0:df:freqf-df; % Frequency axis values