%% Oppgave 5
f0=2e6;%center frequency 
Tp=0.35e-6;%pulse length rms 
fs=50e6;%sampling frequency 
T=2e-6;%time interval [-T,T] 
t=-T:1/fs:T;%time vector 
s=exp(-1/2*(t/Tp).^2).*cos(2*pi*f0*t);%Gaussian signal envelope
figure(1);subplot(2,1,1); plot(t,s);
S=fftshift(abs(fft(s)));
f=linspace(-fs/2,fs/2,length(S));
subplot(2,1,2);;plot(f,S);grid;

dec=4;%decimation factor
sd=s(1:dec:end);%decimated signal
sz=zeros(1,length(s)); sz(1:dec:end)=s(1:dec:end);%sz zero padded between decimated samples
subplot(2,1,1);plot(t,s,t,sz);
Sz=fftshift(abs(fft(sz)));
subplot(2,1,2);plot(f,S,f,Sz);grid;

%% Løsningsforslag:

sp=hilbert(s);
sc=exp(-i*2*pi*f0*t).*sp;
decMax=20;
interpMethod='spline';
useInterp=1;%use interp instead of interp1


for dec=2:decMax,
sd=s(1:dec:end);%decimated signal
td=t(1:dec:end);
decMax

if useInterp,   si=interp(sd,dec);si=si(1:length(s));
else            si=interp1(td,sd,t,interpMethod,0);end;

dBfeil(dec)=10*log10(mean((s-si).^2)/mean(s.^2));
if useInterp,   sic=interp(sc(1:dec:end),dec);sic=sic(1:length(s));
else            sic=interp1(td,sc(1:dec:end),t,interpMethod,0);sic=sic(1:length(s));end;
sic=real(sic.*exp(i*2*pi*f0*t));
dBfeilc(dec)=10*log10(mean((s-sic).^2)/mean(s.^2));
sz=zeros(1,length(s)); sz(1:dec:end)=s(1:dec:end);%sz zero padded between samples
figure(1);
subplot(3,1,1); plot(t,s,t,sz);legend('Original','Decimated')
title(['dec: ' num2str(dec)])
subplot(3,1,2); plot(t,s,t,si,t,sic);;legend('Original','Interpolated','Interpolated baseband')
Sz=fftshift(abs(fft(sz)));
subplot(3,1,3);plot(f,S,f,Sz);grid;
dec
%pause;
end;
figure(3);plot(1:decMax,dBfeil,1:decMax,dBfeilc);axis([2,decMax,-50,0]);grid

%%figure 6

