Reputation: 4349
This is my first using xcorr and I don't seem to understand it. I have a signal signalSubset
within which I'm searching for another signal signalWhole
. The search signal (signalSubset
) is known to be within the signal being search through (signalWhole
). Here's the code:
% signalSubset really is a contained within signalWhole
areSame = isequal(signalSubset, signalWhole(1 : length(signalSubset))); % true
% same length signals - finds best delay (which is zero)
[acor,lag] = xcorr(signalSubset, signalWhole(1 : length(signalSubset)));
[~,I] = max(abs(acor));
lagDiff = lag(I);
% different length signals - totally different delay of -1518
[acor,lag] = xcorr(signalSubset, signalWhole);
[~,I] = max(abs(acor));
lagDiff = lag(I);
Why is it when the signals have different lengths during xcorr
that the index I
is -1518 instead 0 as expected?
Upvotes: 0
Views: 1147
Reputation: 502
xcorr is quite a messy function - whenever I want to calculate correlation's, I prefer to use either SPSS or R.
Nevertheless, in order to use xcorr correctly, you need to pre-align the size of your signals beforehand. The function does not do it for you. This alignment is just seing which is the shortest signal and add 0's to the start and end of the signal.
Then yes, you can calculate xcorr correctly. Code:
if length(dist_RF)<length(dist_LF)
diferenca_tamanho=length(dist_LF)-length(dist_RF);
extra_zeros=floor(diferenca_tamanho/2);
quociente=mod(diferenca_tamanho,2);
% Adicionar zeros inicio
temp=dist_RF;
dist_RF=zeros((length(dist_RF)+2*extra_zeros+quociente),1);
dist_RF((extra_zeros+quociente+1):(length(temp)+(extra_zeros+quociente+1))-1,:)=temp;
elseif length(dist_RF)>length(dist_LF)
diferenca_tamanho=length(dist_RF)-length(dist_LF);
extra_zeros=floor(diferenca_tamanho/2);
quociente=mod(diferenca_tamanho,2);
% Adicionar zeros inicio e fim
temp=dist_LF;
dist_LF=zeros((length(dist_LF)+2*extra_zeros+quociente),1);
dist_LF((extra_zeros+quociente+1):(length(temp)+(extra_zeros+quociente+1))-1,:)=temp;
end
[correl,lags]=xcorr(dist_RF, dist_LF, 'coeff');
if (max(correl)>abs(min(correl)))
correlation_coef=max(correl);
else
correlation_coef=min(correl);
end
delay_signals=find(correlation_coef==correl);
delay_signals=lags(delay_signals);
cross_correlation_value=correlation_coef;
Upvotes: 1