% frequencies of the signals (F1 and F2)
% and sampling frequency (Fs)
F1=500;
F2=2000;
Fs=4000;
% time range: 0 to 2ms, 1us step
t=0:1e-6:2e-3;
x1=cos(2*pi*F1*t);
x2=cos(2*pi*F2*t);
x3=x1+x2;
hold on;
subplot(3,3,1);
plot(t,x1);
subplot(3,3,4);
plot(t,x2);
subplot(3,3,7);
plot(t,x3);
% number of samples for our signal
n=(1:100);
f1=F1/Fs; % digital freqency is the sampled frequency
f2=F2/Fs;
x1=cos(2*pi*f1*n);
subplot(3,3,2);
stem(n,x1);
x2=cos(2*pi*f2*n);
subplot(3,3,5);
stem(n,x2);
x3=x1+x2;
subplot(3,3,8);
stem(n,x3);
% number of samples for the FFT
N=512;
% we calculate just the magnitude (abs), not the phase
X1=abs(fft(x1,N));
X2=abs(fft(x2,N));
X3=abs(fft(x3,N));
% now shift the spectrum to be centered
X1=fftshift(X1);
X2=fftshift(X2);
X3=fftshift(X3);
% digital frequency range will be from -1/2 to 1/2, so
% there is a need to unnormalize it to our sampling
% frequency, which is Fs.
% this means our freq range will go from -Fs/2 to Fs/2
f=Fs.*[-N/2:N/2-1]/N;
% finally we just plot the positive part of everything
subplot(3,3,3);
plot(f(N/2:end),X1(N/2:end));
subplot(3,3,6);
plot(f(N/2:end),X2(N/2:end));
subplot(3,3,9);
plot(f(N/2:end),X3(N/2:end));