%% Answer to Seminar 6 Exercise2
clear
clc

%% Q1 plot the signal in the time domain
load handel;
figure(1)
plot(y);
xlabel('t (second)')
ylabel('y(t)')

%% Q2 plot the signal in the frequency domain
N = size(y,1); % the total num of sampling points
T = N/Fs; % the total sampling time (second)
for i = 1:N
    % Fs is the sampling rate. 
    % fre_x is the range of the signal in the frequency domain.
    fre_x(i) = i/T; 
end
figure(2)
plot(fre_x,abs(fft(y))) 
xlabel('f (H)z')
ylabel('FFT(y)')

%% Q3 plot the spectrogram
figure(3)
spectrogram(y,128,120,[],Fs);

%% Q4 add noise to the signal
% add noise at 1000Hz to the first half of the signal
N1 = floor(N/2);
f1 = 1000;
for i = 1:N1
	S(i,1) = y(i,1) + 0.3*cos(2*pi*f1*i/Fs); 
end

% add noise at 2000Hz to the second half of the signal
f2 = 2000;
for i = N1+1:N
	S(i,1) = y(i,1) + 0.3*cos(2*pi*f2*i/Fs); 
end

figure(4)
plot(S);
xlabel('t (second)')
ylabel('S(t)')
figure(5)
plot(fre_x,abs(fft(S)))
xlabel('f (Hz)')
ylabel('FFT(S)')
figure(6)
spectrogram(S,128,120,[],Fs); 

% add white noise to the signal
for i = 1:N
	S1(i,1) = y(i,1) + 0.3*randn(1,1); 
end
figure(7)
plot(S1);
xlabel('t (second)')
ylabel('S1(t)')
figure(8)
plot(fre_x,abs(fft(S1)))
xlabel('f (Hz)')
ylabel('FFT(S1)')
figure(9)
spectrogram(S1,128,120,[],Fs);
 