%% Circular Convolution with Varying Output Length
% Generate two signals: a five-sample triangular waveform and a first-order FIR filter with response H(z)=1-z^{-1}.

x1 = conv([1 1 1],[1 1 1])
x2 = [-1 1]

%
% Compute their circular convolution with the default output length. The result is equivalent to the linear convolution of the two signals.

ccnv = cconv(x1,x2)

lcnv = conv(x1,x2)

%
% The modulo-2 circular convolution is equivalent to splitting the linear convolution into two-element arrays and summing the arrays.

ccn2 = cconv(x1,x2,2)

nl = numel(lcnv);
mod2 = sum(reshape(lcnv,2,nl/2)')

%
% Compute the modulo-3 circular convolution and compare it to the aliased linear convolution.

ccn3 = cconv(x1,x2,3)

mod3 = sum(reshape(lcnv,3,nl/3)')

%
% If the output length is smaller than the convolution length and does not divide it exactly, pad the convolution with zeros before adding.

c = 5;
z = zeros(c*ceil(nl/c),1);
z(1:nl) = lcnv;

ccnc = cconv(x1,x2,c)

modc = sum(reshape(z,c,numel(z)/c)')

%
% If the output length is equal to or larger than the convolution length, pad the convolution and do not add.

d = 13;
z = zeros(d*ceil(nl/d),1);
z(1:nl) = lcnv;

ccnd = cconv(x1,x2,d)

modd = z'

% Copyright 2015 The MathWorks, Inc.