clear all
close all
clc

%% Riultati Teorici
ii=1:12;
N=2.^ii;

comp_freq=3*(4.*N.*log2(N)-6*N+8)+6*N;
comp_time=(N-1).*(2*N/2-1);

figure
subplot(2,1,1)
plot(N,comp_time); hold on
plot(N,comp_freq)
legend('time','freq')
xlabel('Lunghezza sequenze')
ylabel('Numero di operazioni')
subplot(2,1,2)
plot(N,comp_time); hold on
plot(N,comp_freq)
xlim([0,80])
legend('time','freq')
xlabel('Lunghezza sequenze')
ylabel('Numero di operazioni')

%% Esempio
Fs=100;
Ts=1/Fs;

N=100;
Nh=200;
n=0:N-1;

tn=n*Ts;

x=cos(2*pi*1*tn);

Ntest=200;
for ii=1:12
    Nh(ii)=2^ii;
    h=1/Nh(ii)*ones(1,Nh(ii));
    time_convolution=zeros(1,Ntest);
    for tt=1:Ntest
        [x_filtered,elapsed_time]=convolve(h,x);
        time_convolution(tt)=elapsed_time;
    end
    mean_time_convolution(ii)=mean(time_convolution);
end

for ii=1:12
    Nh(ii)=2^ii;
    h=1/Nh(ii)*ones(1,Nh(ii));
    Nfft=2^nextpow2(length(x)+length(h)-1);
    freq_convolution=zeros(1,Ntest);
    for tt=1:Ntest
        tic;
        x_filtered=ifft(fft(x,Nfft).*fft(h,Nfft));
        x_filtered=x_filtered(1:length(x)+length(h)-1);
        elapsed_time=toc;
        freq_convolution(tt)=elapsed_time;
    end
    mean_freq_convolution(ii)=mean(freq_convolution);
end

figure
plot(Nh,mean_time_convolution);hold on
plot(Nh,mean_freq_convolution)
legend('time','freq');