clear

N=8;
% dt=2*pi/N;
t0=linspace(0,2*pi,N+1)';t=t0(1:N);

% Fourier matrix
FN=zeros(N,N);
for m=0:N-1
    for n=0:N-1
        FN(m+1,n+1)=exp(2*pi*1i*m*n/N);
    end
end

freq=3;
x=sin(freq*t);
xhat=1/sqrt(N)*conj(FN)*x;

figure;
subplot(2,1,1),plot((0:.1:N)'*2*pi/N,sin(freq*(0:.1:N)'*2*pi/N),'b',t0,sin(freq*t0),'ko-')
set(gca,'fontsize',20,'xtick',t0,'xticklabel',{'0','2\pi/8','2(2\pi/8)','3(2\pi/8)','4(2\pi/8)','5(2\pi/8)','6(2\pi/8)','7(2\pi/8)','2\pi'});
axis([0 2*pi -1.1 1.1])
xlabel('Time $t_n$ (radians)','Interpreter','LaTex')
ylabel('$x(t_n)$','Interpreter','LaTex')
title(['Sampling of sin(' num2str(n) 't) for N=',num2str(N)])

subplot(2,1,2),stem(0:N-1,abs(xhat),'k')
set(gca,'fontsize',20);axis([-.5 N-.5 0 2])
xlabel('Frequency $n$','Interpreter','LaTex')
ylabel('$|\hat{x}(n)|$','Interpreter','LaTex')

% aliasing
figure;plot(t,sin(1*t),'ro-',t,sin(9*t),'bo-')
hold on;t1=0:.01:2*pi;
plot(t1,sin(1*t1),'r',t1,sin(9*t1),'b:')
set(gca,'fontsize',20,'xtick',t0,'xticklabel',{'0','2\pi/8','2(2\pi/8)','3(2\pi/8)','4(2\pi/8)','5(2\pi/8)','6(2\pi/8)','7(2\pi/8)','2\pi'});
axis([0 6.28 -1.1 1.1])
xlabel('Time $t_n$','Interpreter','LaTex')
ylabel('$x(t_n)$','Interpreter','LaTex')
legend('sin(t)','sin(9t)')