Search code examples
matlabconvolution

Convolution 2 dirac delta with matlab


So I want to do the following convolution (dirac(t+1)+2*dirac(t-1))*dirac(t-3), but I get a weird value. Normally I would think every thing is shifted with 3 units to the right but the 2*dirac(t-1) stays at t=2 instead of the expected t=4. Why is this?

%Chapter 3_a
clear all 
close all
clc

%% excercise 3

t = -5:0.1:5;
x_1 = dirac(t+1);
idt = x_1 == Inf; % find Inf
x_1(idt) = 1;     % set Inf to finite value


x_2 = 2*dirac(t-1);
idt = x_2 == Inf; % find Inf
x_2(idt) = 1;     % set Inf to finite value

figure
x = x_1 + x_2;
stem(t,x)
hold on

figure
y = dirac(t-3);
idt = y == Inf; % find Inf
y(idt) = 1;     % set Inf to finite value
stem(t,y)

figure
w = conv(x,y)
t_2 = linspace(-5,5,length(w));;
stem(t_2,w)

Solution

  • The problem is in your second to last line,

    t_2 = linspace(-5,5,length(w));

    To understand how to fix this line, it should be first noted that conv knows nothing about the time axes. When you compute w = conv(x,y), it is only assumed that

    1. The time between samples is constant for both inputs x and y.
    2. The finite sequences x and y are thought of as being implicitly extended with zeros to the left and to the right.

    The result w has a length equal to the length(x)+length(y)-1. This is because conv computes the output with the minimum length that ensures that all values outside that length would necessarily be zero (because of assumption 2). For example,

    >> x = [1 1 1];
    y = [1 1 1 1];
    w = conv(x, y)
    
    w =
         1     2     3     3     2     1
    

    As is seen, there is no reference to the time axes in the inputs or in the output. It does not matter, for example, if x starts at t=0 or at t=8. So you need to keep track of the time axes separately. Specifically, if (the specified portions of) x and y start at t=a and t=b respectively, you know that the result w will start at t=a+b. Since you also know the length of w and the time between samples Ts, you can define the time axis for w as a+b + (0:length(w)-1)*Ts.

    In your case, since

    t = -5:0.1:5;
    

    you are defining x and y with time origin t(1) = 5 and sample spacing t(2)-t(2)= 0.1. So you need to create the time axis for w as follows (replace your second to last line):

    t_2 = 2*t(1) + (0:length(w)-1)*(t(2)-t(1));
    

    With this, you will see that the two deltas of x, located at t=-1 and t=1, appear at t=2 and t=4 respectively when you run stem(t_2,w).