% Compute the convolution of f and g

clear
close all
syms x xi 

% Enter f and g
f=(heaviside(x+1)-heaviside(x-1)); % box function
g=x*(heaviside(x)-heaviside(x-1)); % half triangle

% full triangle
%g=(x+1)*(heaviside(x+1)-heaviside(x))+(1-x)*(heaviside(x)-heaviside(x-1)); 

%g=f;
%f=g;

% Compute convolution integral
g2=subs(g,x,x-xi);         % g(x-xi)
f2=subs(f,x,xi);           % f(xi)
h=int(f2*g2,xi,[-10 10]);  % Set large integration range

% Set x values for plotting in t variable
dt = 0.01;
t = [ -5:dt:5 ];

% Change symbolic functions to vectors for plotting
f1=subs(f,x,t);
f1=double(f1);
g1=subs(g,x,t);
g1=double(g1);

%Plot functions
figure(1)
subplot(3,1,1)
plot(t,f1)
xlabel('x')
ylabel('f(x)')
title('f(x) vs x')

subplot(3,1,2)
plot(t,g1)
xlabel('x')
ylabel('g(x)')
title('g(x) vs x')

h1=subs(h,x,t);
h1=double(h1);
subplot(3,1,3)
plot(t,h1)
axis([-5 5 0 1])
xlabel('x')
ylabel('(f * g)(x)')
title('(f * g)(x) vs x')