%% Show discrete convolution
clear all; close all; clc

n = 25;
num_convolves = 10;

x_start = -1;
x_end = 1;

x = linspace(x_start,x_end,n).';
y = zeros(n,1);
y(round(3*n/10):round(7*n/10)) = 1;

plot(x,y,'--*'), shg
%%

X = cell(1,num_convolves); % NOTE THE LAZY CODING PRACTICES HERE!!
Z = cell(1,num_convolves);
Z{1} = y;
X{1} = x;
for k = 2:num_convolves
   Z{k} = conv(y,Z{k-1});

%    I use x_start = -x_end below
   X{k} = linspace(k*x_start+(k-1)*(x_end-x_start)/n,...
      k*x_end - (k-1)*(x_end-x_start)/n,length(Z{k}));
   plot(X{k},Z{k})

   pause(.41)
   shg
end


%% polynomial example
clear all; close all; clc

x = -.99:.01:.99; x = x(:);
% Recall (kidding!) that for Chebyshev polynomials, 2T_mT_n = T_{m+n} + T_{|m-n|}

T3 = [4, 0, -3, 0]';
T5 = [16, 0, -20, 0, 5, 0]';


T3x = polyval(T3,x);
T5x = polyval(T5,x);

subplot(2,1,1), hold on
plot(x,T3x,'g','linewidth',2)
plot(x,T5x,'r','linewidth',2)
%%


conv_vec = conv(T5,T3);
conv_x = polyval(conv_vec,x);

plot(x,conv_x,'c','linewidth',2)

subplot(2,1,2), hold on
semilogy(x,abs(T3x.*T5x - conv_x))

%% double check (using the recursion property)

check_check = (cos(8*acos(x)) + cos(2*acos(x)))/2;

figure(2); semilogy(x,abs(conv_x - check_check))
xlabel('x')
ylabel('absolute difference')
title('error using recursive formula for products')















