% Understanding convolutions part1

% This tutorial is divided into 2 parts. This is the first part devoted 
% to the function manipulations that are necessary to implement convolution and
% the second part is the implementation of discrete convolution


close all
clear all
clc

%%% Function Translation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%
% let f(t) be our function of t. f(t) = 0 for all t < 0 and f(t) = 1 - t/T for all
% t >= 0 and t < T.

% pick up a value for T
T = 3;
% define f as  
f = @(t) double((t >= 0) & (t < T)) .* (1 - t / T);

% generate a set of values for t to evaluate with the functions 
t = -10 : 0.1 : 10;
figure(1)
plot(t, f(t))
xlabel('t')
ylim([-0.1, 1.1])
xlim([-8, 8])
grid on
legend('f(t)')

%%
% we can translate this function to the right or to the left.
% Let's denote the translated version by g(t).
% Translation is simply accomplished by adding the amount we want to shift the function
% to t before we evaluate the function f, in other words, g(t) = f(t + Tau).

Tau = 2;
g = @(t) f(t + Tau);
figure(1)
hold on;
plot(t, g(t))
legend({'f(t)', 'g(t)'})

%%
%  How do you shift the function to the right?
% In the above code the function was shifted to the left by Tau
% Exercise: make a function h(t) = f(?) that shifts f(t) to the right by Tau.  

Tau = 2;
h = @(t) f(t - Tau);       % Solution: subtract Tau from t to shift to the right

figure(1)
hold on 
plot(t, h(t))
legend({'f(t)', 'g(t)', 'h(t)'})


%% Function mirror 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% In this transformation the vertical axis at t = 0 acts as a mirror to the function
% This is accomplished by simple negating the sign of the argument of f
% In other words, fm(t) = f(-t)

fm = @(t) f(-t);

figure(2)
hold on; 
plot(t, f(t));
plot(t, fm(t));
xlabel('t')
ylim([-0.1, 1.1])
xlim([-8, 8])
grid on;
legend({'f(t)', 'fm(t)'});

%% 
% Exercise: construct the mirror functions for g(t) and h(t) and display the
% resulting functions


% Solution: define the mirrored functions by negating the argument t
gm = @(t) g(-t) ;
hm = @(t) h(-t) ;


figure(3)
hold on; 
plot(t, g(t));
plot(t, gm(t));
xlabel('t')
ylim([-0.1, 1.1])
xlim([-8, 8])
grid on;
legend({'g(t)', 'gm(t)'});

figure(4)
hold on; 
plot(t, h(t));
plot(t, hm(t));
xlabel('t')
ylim([-0.1, 1.1])
xlim([-8, 8])
grid on;
legend({'h(t)', 'hm(t)'});
