% eda09_19
% demonsrate effect of windowing on power spectral density
% boxcar window

% standard time/frequency definitions
N=512;
Nf=N/2+1;
Dt=1.0;
tmax=Dt*(N-1); 
t=Dt*[0:N-1]'; 
fmax=1/(2.0*Dt);
Df=fmax/(N/2);
f=Df*[0:N/2,-N/2+1:-1]'; 
Dw=2*pi*Df;
w=Dw*[0:N/2,-N/2+1:-1]'; 

% boxcar window function, W
W = zeros(N,1);
W(1:N/8)=1;
Wtmax = tmax/8;

% timeseriee
w0 = 40*Dw;
d = sin( w0 * t );

% windowed timeseries
Wd = W .* d;

% fourier transform
dfft=fft(d);
Wfft=fft(W);
Wdfft=fft(Wd);

% power spectral density
ds=(Dt^2/tmax)*(abs(dfft).^2);
Ws=(Dt^2/Wtmax)*(abs(Wfft).^2);
Wds=(Dt^2/Wtmax)*(abs(Wdfft).^2);

% time domain plot
figure(1);
clf;
subplot(3,2,1);
set(gca,'LineWidth',2);
hold on;
axis( [0, tmax, -1, 1] );
plot(t,d,'k-','LineWidth',2);
xlabel('time t, s');
ylabel('d(t)');
subplot(3,2,3);
set(gca,'LineWidth',2);
hold on;
axis( [0, tmax, -1, 1] );
plot(t,W,'k-','LineWidth',2);
xlabel('time t, s');
ylabel('W(t)');
subplot(3,2,5);
set(gca,'LineWidth',2);
hold on;
axis( [0, tmax, -1, 1] );
plot(t,Wd,'k-','LineWidth',2);
xlabel('time t, s');
ylabel('W(t)*d(t)');

% frequency domain plot
subplot(3,2,2);
set(gca,'LineWidth',2);
hold on;
axis( [0, fmax, 0, max(sqrt(ds))] );
plot(f(1:Nf),sqrt(ds(1:Nf)),'k-','LineWidth',2);
xlabel('frequency f, Hz');
ylabel('ASD of d');
subplot(3,2,4);
set(gca,'LineWidth',2);
hold on;
axis( [0, fmax, 0, max(sqrt(Ws))] );
plot(f(1:Nf),sqrt(Ws(1:Nf)),'k-','LineWidth',2);
xlabel('frequency f, Hz');
ylabel('ASD of W');
subplot(3,2,6);
set(gca,'LineWidth',2);
hold on;
axis( [0, fmax, 0, max(sqrt(Wds))] );
plot(f(1:Nf),sqrt(Wds(1:Nf)),'k-','LineWidth',2);
xlabel('frequency f, Hz');
ylabel('ASD of Wd)');