Efficient Computation of Convolution
Computing a convolution using
conv when the signals are vectors is generally more efficient than using
convmtx. For multichannel signals,
convmtx might be more efficient.
Compute the convolution of two random vectors,
b, using both
convmtx. The signals have 1000 samples each. Compare the times spent by the two functions. Eliminate random fluctuations by repeating the calculation 30 times and averaging.
Nt = 30; Na = 1000; Nb = 1000; tcnv = 0; tmtx = 0; for kj = 1:Nt a = randn(Na,1); b = randn(Nb,1); tic n = conv(a,b); tcnv = tcnv+toc; tic c = convmtx(b,Na); d = c*a; tmtx = tmtx+toc; end t1col = [tcnv tmtx]/Nt
t1col = 1×2 0.0006 0.0227
t1rat = tcnv\tmtx
t1rat = 40.1225
conv is about two orders of magnitude more efficient.
Repeat the exercise for the case where
a is a multichannel signal with 1000 channels. Optimize
conv's performance by preallocating.
Nchan = 1000; tcnv = 0; tmtx = 0; n = zeros(Na+Nb-1,Nchan); for kj = 1:Nt a = randn(Na,Nchan); b = randn(Nb,1); tic for k = 1:Nchan n(:,k) = conv(a(:,k),b); end tcnv = tcnv+toc; tic c = convmtx(b,Na); d = c*a; tmtx = tmtx+toc; end tmcol = [tcnv tmtx]/Nt
tmcol = 1×2 0.1428 0.0646
tmrat = tcnv/tmtx
tmrat = 2.2111
convmtx is about three times as efficient as
h — Input vector
Input vector, specified as a row or column.
n — Length of vector to convolve
Length of vector to convolve, specified as a positive integer.
his a column vector of length
n, and the product of
Aand a column vector,
x, of length
nis the convolution of
his a row vector of length
(m+n-1), and the product of a row vector,
x, of length
Ais the convolution of
A — Convolution matrix
Convolution matrix of input
h and the vector
x, returned as a matrix.
convmtxuses the function
toeplitzto generate the convolution matrix.
convmtxhandles edge conditions by zero padding.