I am trying to implement Matlab's cross correlation function but I can't seem to replicate the results obtained when using Matlab's built in function "xcorr".
Documentation for xcorr can be found HERE.
Looking at the Matlab documentation it seems as though the cross correlation is implemented as
$$ R_{xy}[m] = \left.\begin{cases} \sum_{n=0}^{N - m - 1} x[n + m] y[n] & m \geq 0\\ \\ R_{yx}[-m] & m < 0\\ \end{cases} \right\} $$
Or equivalently as
$$ R_{xy}[m] = \left.\begin{cases} \sum_{n=1}^{N - m} x[n + m] y[n] & m \geq 0\\ \\ \sum_{n=1}^{N + m} y[n - m] x[n] & m < 0\\ \end{cases} \right\} $$
if x and y have indexes starting at 1.The result will then be C, where
$$ C(m) = R_{xy}(m - N) \hspace{1cm} \text{for} \hspace{1cm} m = 1, 2,...,2N - 1. $$
The implementation of this formula in Matlab is shown below:
function [result] = myXCorr(A , B)
%Implementation of the Cross Coorelation Function
N = size(A,2);
M = size(B,2);
result = zeros(1, N + M - 1 );
len = size(result,2);
for m = 1 : len
arg = (m - N);
if(arg < 0)
negativeCondition = 1;
limit = N + arg;
else
negativeCondition = 0;
limit = N - arg;
end
for n = 1:limit
if(negativeCondition == 0)
result(m) = result(m) + A(arg + n) + B(n);
else
result(m) = result(m) + A(n) + B(n - arg);
end
end
end
end
This implementation does not produce the same results as Matlab and I can't seem to find out what the error is.The plots of the autocorrelation's are shown below.
A = 1:1:10;
B = 1:1:10;
myResult = myXCorr(A,B);
mResult = xcorr(A,B);
lag = -9:1:9;
plot(lag, myResult);
plot(lag, mResult);
Autocorrelation using my function:
Autocorrelation using "xcorr":
Does anyone know what 'm doing wrong here? Any help will be appreciated.