# How to understand the discrete and continuous convolution in matlab?

For example,I want to calculate the convolution of two continuous signal in matlab as the image shows. Indeed, I chose to discrete the signal to compute in matlab.

Obiviously, the 1st and 3rd are right, I think the difference of discrete and continous convolution might be the reason, but why?

As Hilmar said you need to be careful of the difference between circular convolution and linear convolution. Linear convolution in the time domain translates to multiplying discrete time fourier transforms (DTFT) or continuous time fourier transforms (CTFT) in frequency and I'm sure you've seen this done.

But as you know, the DTFT and CTFT are infinite sums/integrals so cannot actually be computed by a computer. The discrete fourier transform (DFT) can be computed by MATLAB though and it uses an efficient algorithm called the fast fourier transform (FFT) which runs on the order of NlogN time, where N is the length of the signal. You can look up that multiplying two DFTs is equivalent to performing circular convolution which just "wraps" the signal around (read Oppenheim's DSP book or wikipedia).

Check this out which shows the difference between performing linear convolution, how to use the fft() function in MATLAB to get the result, and how circular convolution is different.

clear,close all;

a = [zeros(40,1); ones(20,1); zeros(41,1)];
b = [zeros(50,1); ones(30,1); zeros(21,1)]/2;
c = conv(a,b);
nfft = length(a)+length(b)-1;
A = fft(a,nfft);
B = fft(b,nfft);
C = A.*B;
d = ifft(C);
e = ifft(fft(a).*fft(b));

figure
subplot(6,1,1)
plot(a)
title('a[n]')
subplot(6,1,2)
plot(b)
title('b[n]')
subplot(6,1,3)
plot(c)
title('Convolution in time domain')
subplot(6,1,4)
plot(d)
title('Convolution by multiplying in freq. domain')
subplot(6,1,5)
plot(e)
title('Circular convolution by multiplying in freq. domain')


If you convolve two signals of length $$M$$ and $$N$$ the result will have a length of $$M+N-1$$. In order to produce this result, your FFT length must be (at least) $$M+N-1$$. You need to zero pad the signal before doing the FFT, otherwise you get time domain aliasing.

Time discrete signals are assumed to be periodic in frequency and frequency discrete signals are assumed to be periodic in time. Multiplying two FFTs implements "circular" convolution, not "linear" convolution. You simply have to make your "period" long enough so that the result of the linear convolution fits into it without wrapping around.

The right (but inefficient) code would be something like

n = length(a)+length(b)-1;
z = ifft(fft(a,n).*fft(b,n);