Convolution in MATLAB: Source Code and Explanation
Advertisement
This document explores convolution using MATLAB, providing example source code and explanations. Convolution is a fundamental operation in signal processing. It’s worth noting that convolving two signals in the time domain is equivalent to multiplying their frequency spectra. The process involves flipping one signal, shifting it, and then multiplying its elements with the corresponding elements of the other signal.
The general formula for the convolution output z[n] is:
MATLAB Code Example
The following MATLAB code demonstrates convolution without using the built-in conv function, followed by a demonstration using the built-in function for comparison.
clc;
clear all;
x = [1 2 3 4 5]; % First signal
h = [1 2]; % Second signal (impulse response)
% Manual convolution calculation
y(1) = x(1)*h(1);
y(2) = x(2)*h(1) + x(1)*h(2);
y(3) = x(3)*h(1) + x(2)*h(2);
y(4) = x(4)*h(1) + x(3)*h(2);
y(5) = x(5)*h(1) + x(4)*h(2);
y(6) = x(5)*h(2);
y % Outputs the result of convolution between x and h vectors
len = length(y) % Length of result(y length) = length(x) + length(h) - 1
% MATLAB built-in convolution function 'conv'
y1 = conv(x,h) % Output as per matlab built in function
len1 = length(y1)
plot(y-y1);
title('Difference between MATLAB conv function and our code');
Explanation:
- Initialization: The code starts by clearing the command window and workspace. Two vectors,
xandh, are defined, representing the two signals to be convolved. - Manual Convolution: The code then performs the convolution manually, calculating each element of the output vector
y. This illustrates the sliding-and-summing process of convolution. Each element ofyis computed based on the formula provided earlier. - Output: The
yvariable, containing the result of the manual convolution, is displayed. The length of the resultyis calculated, verifying that it equals the sum of lengths of input vectorsxandhminus 1. - Built-in
convFunction: The code then uses MATLAB’s built-inconvfunction to perform the same convolution. The result is stored iny1. - Comparison: Finally, the code plots the difference between the manually calculated convolution (
y) and the result from theconvfunction (y1). Ideally, this difference should be zero, confirming that the manual implementation is correct. - Length:
len1stores the length of the convolution result produced by the built-inconvfunction.
Important Considerations
- The length of the resulting vector
yfrom the convolution of vectorsxandhis alwayslength(x) + length(h) - 1.
Advertisement
RF