%convolve two triangle functions, both with and without padding.
%to demonstrate wrap around.
%
%clear any old variables and figure windows
clear all
close all

%half length of triangle
T=1;

%time step size in seconds
dt=0.01;

%length of vectors to create
N=2*T/dt;

%define a 0
ZERO=1e-10;
%create time vectors
t=linspace(0,2*T,N);
tt=linspace(0,4*T,2*N);
ttt=linspace(0,4*T-dt,2*N-1);

%create triangle
f0=t(1:N/2);
x1=[f0,fliplr(f0)];

%w-domain convolution and scale by dt to match the integral
w1=fft(x1);
x2=ifft(w1.*w1)*dt;

%is it real?
if imag(x2)*imag(x2') < ZERO
  x2=real(x2);
end

%zero pad
x3=zeros(1,2*N);
x3(1:N)=x1;

%w-domain convolution and scale by dt to match integral
w3=fft(x3);
x4=ifft(w3.*w3)*dt;

%is it real?
if imag(x4)*imag(x4') < ZERO
  x4=real(x4);
end

xmin=0;
xmax=2;
ymin=0;
ymax=1;

subplot(5,1,1)
plot(t,x1)
text(1,0.5,'x1')
axis([xmin xmax ymin ymax])

subplot(5,1,2)
plot(t,x2)
text(1,0.5,'x2=ifft(X1.*X1)')
axis([xmin xmax ymin ymax])

xmax=4;
subplot(5,1,3)
plot(tt,x3)
text(1,0.5,'x3')
axis([xmin xmax ymin ymax])

subplot(5,1,4)
plot(tt,x4)
text(0.25,0.25,'x4=ifft(X3.*X3)')
axis([xmin xmax ymin ymax])

subplot(5,1,5)
plot(ttt,conv(x1,x1)*dt)
text(0.25,0.25,'conv(x1,x1)')
axis([xmin xmax ymin ymax])
xlabel('time (s)')

orient tall
print -dps wrap.ps
