%file name : CirConv.m
% Circular Convolution of two sequences using DFT and IDFT.
MatLab Version 5.2
% This Matlab program calculates the circular convolution
% of the two sequences using DFT and IDFT. The program displays
% result on the screen and sketches sequences in the figure.
% Inputs: Causal sequences x(n) and h(n)
% Ouputs: Display of y(n) = circular convolution of x(n) and h(n).
% Sketch of x(n), h(n) and y(n).
% Assumptions: The lengths of x(n) and h(n) should be equal.
% Zero padding is absent.
%-------------------------------------------------------------------------
%------ next part accepts sequences x(n) and h(n) ------------------------
xn = input('Enter the sequence x(n)= '); % sequence x(n)
hn = input('Enter the sequence h(n) = '); % sequence h(n)
%-------- next part calculates DFT X(k) of x(n) --------------------------
[N,M] = size(xn); % These statements determine
if M~=1, % the size of the vector xn
xn = xn'; % suitable for evaluating
N = M; % the DFT. Here N is the length
end % of the DFT.
Xk = zeros(N,1); % The values of DFT X(k) initialized to zeros
n = 0:N-1; % Index n varies from 0 to N-1
for k = 0:N-1 % This 'for' loop implements
Xk(k+1) = exp(-j*2*pi*k*n/N)*xn; % the DFT equation and calculates
end % X(k) for k = 0 to N-1.
%-------- next part calculates DFT H(k) of h(n) --------------------------
[N,M] = size(hn); % These statements determine
if M~=1, % the size of the vector hn
hn = hn'; % suitabke for evaluating
N = M; % the DFT. Here N is the length
end % of the DFT.
Hk = zeros(N,1); % The values of DFT H(k) initialized to zeros
n = 0:N-1; % Index n varies from 0 to N-1
for k = 0:N-1 % This 'for' loop implements
Hk(k+1) = exp(-j*2*pi*k*n/N)*hn; % the DFT equation and calculates
end % H(k) for k = 0 to N-1.
%----------- next part multiplies the two DFTs X(k) and H(k) -------------
Yk = Xk.* Hk; % Multiplication of two DFTs is equivalent to
% 'Circular convolution' of corresponding time
% domain sequences x(n) and h(n).
%-------- next part calculates IDFT of Y(k) to get y(n) -------------------
[N,M] = size(Yk); % These statements determine
if M~=1, % the size of the vector Y(k)
Yk = Yk.'; % suitable for evaluating the
N = M; % IDFT. Here N is the length
end % of the DFT.
yn = zeros(N,1); % The sequence values are initialized to zeros
k = 0:N-1; % Index k varies from 0 to N-1
for n = 0:N-1 % This 'for' loop implements
yn(n+1) = exp(j*2*pi*k*n/N)*Yk; % the IDFT formula and calculates
end % y(n) for n = 0 to N-1
yn = yn/N; % Divide by N as per IDFT formula
disp('yn =');
disp(yn); % display the circular convolution of
% x(n) and h(n) i.e. y(n) on the screen.
%--------------- End of the program -------------------------------------