Friday 9 September 2016

DSP - Circular Convolution of Discrete Time Signals (Scilab Code with Plot)

Scilab Code:

//Circular Convolution of x(n) and h(n) is given by:
//Summation of x(n).h(m-n) from 0 to N-1
//where, N = length of sequences
//Both the sequences start from the origin
clc; close; clear;

x = input("Enter the first sequence: ");
h = input("Enter the second sequence: ");

//perform zero-padding to make lengths equal
length_diff = length(x) - length(h);
if length_diff>0 then
    h = [h, zeros(1:abs(length_diff) )];
else
    x = [x, zeros(1:abs(length_diff) )];
end

x_origin = 1;
h_origin = 1;
x_lower = -(x_origin - 1);     //lower range of x
h_lower = -(h_origin - 1);     //lower range of h
x_upper = length(x) - x_origin;     //upper range of x
h_upper = length(h) - h_origin;     //upper range of h

//Create the x_matrix and h_matrix
len = length(x);
for i = 1:len
    x_mat(i, 1) = x(i);
    j = i;
    for c = 1:len
        h_mat(j, i) = h(c);
        j = j + 1;
        if j == (len+1)
            j = j - len;
        end
    end
end

y = h_mat * x_mat;
y = y';

disp(x, "x = ");
disp(h, "h = ");
disp(x_mat, "x_mat = ");
disp(h_mat, "h_mat = ");
disp(y, "Circular Convolution = ");

subplot(3, 1, 1);
plot2d3(x_lower:x_upper, x, style=color("green"));
xtitle("First Sequence","n","x(n)");
a = gca();
a.x_location = "origin";
a.y_location = "origin";
a.children.children(1).thickness = 2;

subplot(3, 1, 2);
plot2d3(h_lower:h_upper, h, style=color("red"));
xtitle("Second Sequence","n","h(n)");
a = gca();
a.x_location = "origin";
a.y_location = "origin";
a.children.children(1).thickness = 2;

subplot(3, 1, 3);
n = 0:(len-1);
plot2d3(n, y, style=color("blue"));
xtitle("Circular Convolution: x(n) x h(n)","n","y(n)");
a = gca();
a.x_location = "origin";
a.y_location = "origin";
a.children.children(1).thickness = 2;


Console I/O:




Plot:





No comments:

Post a Comment