DSPRelated.com
Code

Circular Convolution

kaz - March 3, 2012 Coded in Matlab

The output of convolving two finite streams builds up from zero and tails off towards zero.

In some cases e.g. modelling or playing a test vector in actual hardware, this is undesirable and will lead to false errors. The remedy is to remove this start/tail of convolution. This can be done either manually provided the vector end wraps up in phase with its start, or the convolution can be forced to be circular i.e. take both ends of vectors into account as shown in the  snippet below.

In this code the first input (h) is assumed shorter otherwise you will need to make a simple swap.

Note:The output of function "filter(h,1,x)" becomes equivalent to that "conv(h,x)" provided you take first half of latter i.e. y = y(1:length(x));

%circular convolution
%for testing you may use:
h = fir1(20,.3);
x = randn(1,1024);

%function y = conv_circ(h,x)

y = conv(h,x);

L1 = length(h);
L2 = length(x);

%add end to start, add start to end
temp = y(1:L1-1);
y(1:L1-1) = y(1:L1-1) + y(L2+(1:L1-1));
y(L2+(1:L1-1)) = y(L2+(1:L1-1)) + temp;

%compare to direct convolution
y2 = conv(h,x);
plot(y,'o-');hold
plot(y2,'r.--')
legend('circular','direct')