I understand that if we have two vectors -say X and Y, we can calculate their convolution in Matlab using Z = conv(X, Y). There's another way to do this which is, as described on Mathworks.com, through the convolution matrix:
n = length(Y);
Z = convmtx(X,n)*Y;
I have two questions:
- Why use the convolution matrix if we can rely on
conv(X, Y)? - The cited docs say that the former method is more efficient but unfortunately they don't explain why. Is it mainly due to the fact that the second method requires the computation and allocation of
length(Y)or is there more to it (is the matrix multiplication more efficient than a convolution operation, etc.)?
Thank you!
Edit: I contacted Mathworks.com as well and I thought I'd share their answer:
You can see for yourself that conv is indeed more efficient if you run this code.
tfs = 0; tsl = 0;
Nt = 20; sh = 500;
for kj = 1:Nt
q = randn(10000,1); h = randn(sh,1);
tic
fst = conv(q,h);
tfs = tfs+toc;
tic
slo = convmtx(q,sh); slo = slo*h;
tsl = tsl+toc;
end
tfs = tfs/Nt; tsl = tsl/Nt; tsl/tfs
You can see that conv is faster by a factor of about 120. There are a few reasons why that is the case, but the most important may be that conv is (almost) a built-in compiled function, whereas convmtx is coded in the MATLAB language and is interpreted when called (i.e., it is parsed, subjected to a layer of type checking, etc.). Moreover, when you call convmtx you create many copies of the input array, even though you really need only one.