Circular convolution (without built in
function)
% Circular Convolution in MATLAB
clc;
clear;
% Input two sequences
x = input('Enter the first sequence x[n]: ');
h = input('Enter the second sequence h[n]: ');
% Ensure the sequences have the same length by zero-padding the shorter one
N = max(length(x), length(h));
x = [x, zeros(1, N - length(x))];
h = [h, zeros(1, N - length(h))];
% Initialize the output sequence
y = zeros(1, N);
% Perform circular convolution
for n = 1:N
for k = 1:N
index = mod(n - k, N); % Circular index
if index < 0
index = index + N; % Handle negative modulo
end
y(n) = y(n) + x(k) * h(index + 1); % Add 1 for MATLAB 1-based indexing
end
end
% Display the result
disp('The result of the circular convolution y[n] is:');
disp(y);
% Plot x[n]
n=0:N-1;
subplot(3, 1, 1);
stem(n, x, 'filled');
title('Input Sequence x[n]');
xlabel('n');
ylabel('x[n]');
grid on;
% Plot h[n]
subplot(3, 1, 2);
stem(n, h, 'filled');
title('Input Sequence h[n]');
xlabel('n'); ylabel('h[n]');
grid on;
% Plot y[n]
subplot(3, 1, 3);
stem(n, y, 'filled');
title('Circular Convolution Result y[n]');
xlabel('n');
ylabel('y[n]');
grid on;
Circular convolution (with built in function)
% Circular Convolution using cconv
clc;
clear;
% Input two sequences
x = input('Enter the first sequence x[n]: ');
h = input('Enter the second sequence h[n]: ');
% Length of the circular convolution (optional, default is max(length(x), length(h)))
N = input('Enter the length of circular convolution (optional, press Enter for default): ');
if isempty(N) % If no length is specified, use default length
N = max(length(x), length(h));
end
% Perform circular convolution using cconv
y = cconv(x, h, N);
% Display the result
disp('The result of the circular convolution y[n] is:');
disp(y);
% Plot the input sequences and the result figure;
% Plot x[n]
n=0:length(x)-1;
subplot(3, 1, 1);
stem(n, x, 'filled');
title('Input Sequence x[n]');
xlabel('n'); ylabel('x[n]');
grid on;
% Plot h[n]
n= 0:length(h)-1;
subplot(3, 1, 2);
stem(n, h, 'filled');
title('Input Sequence h[n]');
xlabel('n'); ylabel('h[n]');
grid on;
% Plot y[n]
n= 0:length(y)-1;
subplot(3, 1, 3);
stem(n, y, 'filled');
title('Circular Convolution Result y[n]');
xlabel('n');
ylabel('y[n]');
grid on;