The problem when using diag(conv2(x,x,k));
is that you are calculating something much larger (the whole 2d matrix) and then you keep only the diagonal. It could be expensive depending on the size of your signals. You can try with
n = 500; m = 50;
x = rand(n,1);
k2 = rand(m,m);
tic; res1 = diag(conv2(x,x,k2)); toc;
tic;
res2 = zeros(n+m-1,1);
for k = 1:n+m-1
imin = k+1-min(k,m); imax = min(k,n);
jmin = max(1,k-n+1); jmax = min(k,m);
res2(k) = x(imax:-1:imin)'*k2(jmin:jmax,jmin:jmax)*x(imax:-1:imin);
end
toc;
norm(res1-res2)
It works faster than the other option for many cases I have tried. One ouput can is, for instance
>> script
Elapsed time is 0.012753 seconds.
Elapsed time is 0.006541 seconds.
ans =
1.5059e-12
I do not know how large are your signals or your kernel, so you can try.