MATLAB: Regarding calculating convolution in Matlab.

convolutiongraph

Just wondering that why my calculation of conv(h,x) is not correct? The red curve in the picture is what I expected for the convolution.
RC=1;
u=1;
t=linspace(-2,10,5000);
x=zeros(1,5000);
for k=1:length(t)
if(t(k)<0)
x(k)=0;
elseif(t(k)>=0 && t(k)<2)
x(k)=0.5;
else
x(k)=0;
end
end
subplot(1,2,1);
plot(t,x,'LineWidth',2);
title('x(t)');
h=zeros(1,5000);
for k=1:length(t)
if(t(k)<0)
h(k)=0;
else
h(k)=RC*exp(-t(k))*u;
end
end
subplot(1,2,2);
plot(t,h,'LineWidth',2);
title('h(x)');
con=conv(h,x);
t=linspace(-2,10,length(con));
hold on;
plot(t,con,'LineWidth',2);

Best Answer

Hi Huidong,
When you do c = conv(a,b) the array length of c is the sum of the array lengths of a and b, minus one. The resulting step size is the same. For the output of conv, you have a longer time array with the same spacing. When you did the second linspace command you cut the array spacing in half, which is not allowed.
Also, you are trying to reproduce a convolution integral in the time domain. Conv does a sum, so you need to multiply by the array step width delt. Replacing the last four lines of code with
delt = t(2)-t(1);
con = conv(h,x)*delt;
t = (1:length(con))*delt - 4; % new time array
hold on;
plot(t,con,'LineWidth',2);
xlim([-2 10])
hold off
should reproduce the example.
After the convolution you want something to start happening at t = 0. If you look at the delays in starting out from the beginning in the x and h waveforms, you should be able to see what the -4 is about in the new time array.
p.s. I replaced subplot(1,2,n) with subplot(2,1,n) so the aspect ratio would be the same as in the example.