Wednesday, September 4, 2013

Graphical Convolution in MATLAB

A question was posted during lecture today on how to visualize the limits of integration when performing graphical convolution. I find properly defining the limits of integration to be one of the more challenging aspects of carrying out the convolution. Depending on which function you flip and shift it can make the task easier or harder. So through experience, or just trying it both ways, you can determine which function to flip and shift.

If i'm having trouble with the limits of the integral I'll just go ahead and plot the result using MATLAB. Here's the code and resulting figure for one of the problems.

fs = 1024;
dt = 1/fs;
tmin = -6;  % tmin/tmax need to be the same otherwise axis is skewed
tmax = 6;
t = tmin:1/fs:tmax;

To = 1;
x = stepfun(t, -To) - stepfun(t, To);
h = stepfun(t, 0).*exp(-t);
z = conv(h, x, 'same') * dt;    % Properly scale convolution

figure, plot(t, x), hold all, plot(t, h), plot(t, z)
grid on, xlabel('t'), legend('x(t)', 'h(t)', 'conv(x(t), h(t))')

Here was a another problem that required five different ranges in the result. As you can see it can be helpful to sometimes plot out the result to verify your results, or to aid in defining the integration limits.
fs = 1024;
dt = 1/fs;
tmin = -2;  % tmin/tmax need to be the same otherwise axis is skewed
tmax = 2;
t = tmin:1/fs:tmax;

To = 1;
Ts = To/2;

x = stepfun(t, 0) - stepfun(t, Ts);
h = (1 - t/To).*(stepfun(t, 0) - stepfun(t, To));
z = conv(h, x, 'same') * dt;

plot(t, x), hold all, plot(t, h), plot(t, z)
grid on, xlabel('t'), legend('x(t)', 'h(t)')

x1 = (t-t.^2/(2*To)).*(stepfun(t, 0) - stepfun(t, Ts));
idx = find(x1 ~= 0);
plot(t(idx), x1(idx), 'o')

x2 = (Ts*(Ts-2*t+2*To)/(2*To)).*(stepfun(t, Ts) - stepfun(t, To));
idx = find(x2 ~= 0);
plot(t(idx), x2(idx), 'o')

x3 = (Ts-t+To).^2/(2*To).*(stepfun(t, To) - stepfun(t, Ts + To));
idx = find(x3 ~= 0);
plot(t(idx), x3(idx), 'o')


No comments: