% ------------------------------------------------------------
% PERIODIC vs NON-PERIODIC SIGNALS DEMO
% Δείχνει τη διαφορά μεταξύ αρμονικού σήματος και θορύβου
% ------------------------------------------------------------

clear; close all; clc;

fs = 44100;              % sample rate
t = 0:1/fs:1;            % 1 sec

f0 = 500;                % θεμελιώδης συχνότητα

% -----------------------------
% 1. Περιοδικό σήμα (αρμονικό)
% -----------------------------
x_periodic = sin(2*pi*f0*t) + 0.5*sin(2*pi*2*f0*t) + 0.3*sin(2*pi*3*f0*t);

% -----------------------------
% 2. Μη περιοδικό σήμα (θόρυβος)
% -----------------------------
x_noise = randn(size(t));

% -----------------------------
% FFT
% -----------------------------
N = length(t);

X1 = abs(fft(x_periodic));
X2 = abs(fft(x_noise));

f = (0:N-1)*(fs/N);

% -----------------------------
% PLOTS
% -----------------------------
figure;

% Περιοδικό - time
subplot(2,2,1)
plot(t(1:1000), x_periodic(1:1000))
title('Periodic signal (time)')
xlabel('Time (s)'), ylabel('Amplitude'), grid on

% Περιοδικό - spectrum
subplot(2,2,2)
plot(f(1:N/2), X1(1:N/2))
title('Periodic signal (spectrum)')
xlabel('Frequency (Hz)'), ylabel('Magnitude'), grid on

% Μη περιοδικό - time
subplot(2,2,3)
plot(t(1:1000), x_noise(1:1000))
title('Non-periodic signal (time)')
xlabel('Time (s)'), ylabel('Amplitude'), grid on

% Μη περιοδικό - spectrum
subplot(2,2,4)
plot(f(1:N/2), X2(1:N/2))
title('Non-periodic signal (spectrum)')
xlabel('Frequency (Hz)'), ylabel('Magnitude'), grid on

% -----------------------------
% PLAY SOUND
% -----------------------------
disp('Periodic signal...')
sound(x_periodic, fs)
pause(1.5)

disp('Noise signal...')
sound(x_noise, fs)