%% make some vectors
T = 1000;
t = 1:T;

%% show t
t
% show size of t
size(t)

t = t';
size(t)

%% make sinusoids

f1 = sin(2*pi*t/T);
f2 = sin(2*pi*t/T*3+.2);
f3 = cos(2*pi*t/T*50);

f = f1+f2+f3;


%% plot functions
figure(1);
plot(t,[ f1 f2 f3 f],'LineWidth',2);
xlabel('t');
legend('f_1','f_2','f_3','f');


%% fourier transform
F = fftshift(fft(f));
% get rid of round-off errors
F = F.*(abs(F)>1e-10);
% create frequency axis
omega = T/2*linspace(-1,1,T+1);
omega = omega(1:end-1);
figure(2);
% plot magnitude
subplot(211);plot(omega,log(abs(F)+1));
% plot phase
subplot(212);plot(omega,angle(F));


%% noisy observations

noise_std = 1;
n = randn(T,1)*noise_std;
size(n)
% histogram of noise
figure(3);hist(n,100);

y = f+n;
figure(4);subplot(211);plot(t,[f ]);
subplot(212);plot(t,y);

Y = fftshift(fft(y));
Y = Y.*(abs(Y)>1e-10);

figure(5);
% plot magnitude
subplot(211);plot(omega,log(abs(Y)+1));
% plot phase
subplot(212);plot(omega,angle(Y));


%% remove noise with frequency-domain filter
H = exp(-omega.^2/20000);
H = H';
figure(6);subplot(211);plot(omega,H);

F_hat1 = Y.*H;
f_hat1 = real(ifft(fftshift(F_hat1)));
subplot(212);plot(t,f_hat1);

MSE_1 = sum((f-f_hat1).^2)
title(['Frequency-domain linear filter output, MSE = ' num2str(MSE_1)]);

%% remove noise with time-domain filter
h = fspecial('gaussian',[100,1],2);
f_hat2 = conv(y,h,'same');
figure(7);plot(t,f_hat2);

MSE_2 = sum((f-f_hat2).^2)
title(['Time-domain linear filter output, MSE = ' num2str(MSE_2)]);

%% remove noise with a nonlinear filter
F_hat3 = Y.*(abs(Y)>1e2);
f_hat3 = ifft(fftshift(F_hat3));
figure(8);plot(t,[f_hat3 ]);
MSE_3 = sum((f-f_hat3).^2)
title(['Nonlinear filter output, MSE = ' num2str(MSE_3)]);





