2
votes

I have 2 signals of different lengths where the shorter signal is the same as the longer n samples shifted. I want to find the maximum normalized cross-correlation between these two signals. Since it is normalized should give 1. The xcorr function lags vary from -441 to 441 samples.

This will be used for slightly different signals later on, but for now I'm trying with equal signals.

Zero-padding (as I've done in the image) gives me a wrong correlation since the zeros become a part of the correlation calculation.

Any ideas how to accomplish this?

2
hmmm, I don't think the zero padding should give you the wrong solution, do you use matlab xcorr? - GameOfThrows
This is not super duper correct but: say you have signal A and B, both each size (B is the blue one in your pic), the you could just xcorr(A(A~=0), B(A~=0)) - rst
"xcorr" with the 'coef' option turned on provides a correlation (in this specific case) of 0.52 and not 1, and i am assuming that this is because of the zeropadding not "allowing" a maximum correlation of 1. @RobertStettler , so basically you just do not include zero values in the correlation calculation? - Rekeal
Yes, thats why I said "not super duper correct", If it is clear, that always the first n and the last m entries are zero, then you could to something with find(..., 'first') and flip(...) - rst

2 Answers

1
votes

If you want to remove the first and last zeros of a vector you can use this here

A = A(find(A~=0, 1, 'first'):find(A~=0, 1, 'last'));

To use it directly in your correlation, try to use this here (where A is your red line and B the blue one)

xcorr(A(find(A~=0, 1, 'first'):find(A~=0, 1, 'last')), B(find(A~=0, 1, 'first'):find(A~=0, 1, 'last')));
1
votes

Suppose x and y are the shorter and longer signals you have.

nx = length(x);
ny = length(y);
cc = nan(1,ny-nx+1);
for ii = 0 : ny-nx
  id = (1:nx) + ii;
  cc(ii+1) = sum(x.*y(id))/(sqrt(sum(x.^2)*sum(y(id).^2)));
end
[ccmx,idmx] = max(cc);

Now you have the position of the maximum cross coefficient.

if the lag starts from -441 as you gave (where x and y are aligned at the left). The max should be at lag=idmx-442.