%Autocorrelation function estimator - effect of spatio/temporal averaging
%Script to investigate distribution of the complex autocorrelation function estimate
% and estimators for power, mean frequency and bandwidth
% effect of averaging between uncorrelated datasegments
%Uses Csignaldemo.m
%06.08.02  Hans Torp
clear;
P=1;
w1=0.5;
B=0.1;
N=3;%packet size
Nsamples=4000;
M=4;%Averaging number
for m=1:M,
    z=Csignaldemo(P,w1,B,Nsamples);%signal
    zn=Csignaldemo(P/10,0,10,Nsamples);%white noise
    z=z+zn;
    z1=z(1:end-1);
    z2=z(2:end);
    b=ones(N,1)/N;%averaging filter coefficients
    R0(:,m)=filter(b,1,conj(z1).*z1);
    R1(:,m)=filter(b,1,conj(z1).*z2);
end;
w1est=angle(R1(:,1));
w1mean1=mean(angle(R1),2);
w1mean2=angle(mean(R1,2));
stdw1=std(w1est)
stdw1mean1=std(w1mean1)
stdw1mean2=std(w1mean2)

Pest=R0(:);
%w1est=angle(R1(:));
ro=R1(:)./R0(:);
Best=sqrt(2*abs((1-abs(ro))));
maxR1=max(abs(R1(:)));
figure(1);
subplot(2,1,1);plot(R1(:),'.');
axis('image');axis(maxR1*[-1,1,-1,1]);grid;
xlabel('real(R1)');ylabel('imag(R1)');
subplot(2,1,2);
plot(abs(R1),angle(R1),'.');grid;
xlabel('abs(R1)');ylabel('angle(R1)');ylim([-pi,pi]);
pause;
figure(2);
subplot(3,1,1);hist(Pest,0:0.1:5*P);xlabel('Power estimate');
subplot(3,1,2);hist(w1est,-pi:0.05:pi);xlabel('Mean freq. estimate');
subplot(3,1,3);hist(Best,0:0.1:2);xlabel('Bandwidth estimate');
biasw1=mean(w1est)-w1
stdw1=std(w1est)
pause;
figure(3); 
subplot(2,1,1);plot(R1(:),'b.');%axis('equal');grid;
axis('image');axis(maxR1*[-1,1,-1,1]);grid;
hold on;plot(mean(R1,2),'r.');hold off;
xlabel('R1 real part'):ylabel('R1 imag. part');
legend('R1','mean(R1)');
subplot(2,1,2);
hist([w1est,w1mean2],-pi:0.02:pi);
xlabel('phase angle [rad]');
legend('angle(R1)','angle(mean(R1))');
axis('tight');

