Auto and Cross correlation in matlab without xcorr function
This page covers Auto correlation matlab code and Cross correlation in matlab with and without using matlab inbuilt xcorr function.
Correlation determines how much two signals or vectors are similar or different in phase and magnitude. There are two types auto correlation and cross correlation. correlation is maximum when two signals are similar. correlation is equivalent to multiplying the complex conjugate of frequency spectrum of one signal by the frequency spectrum of the other.
In auto correlation, signal is correlated to itself or with shifted version of it. In cross correlation two different time series signals are correlated. The example below is for cross correlation. If one set both in1 and in2 as same vectors ( or append zeros initially in one) then it becomes auto correlation.
correlation output z[n] = ∑X[k] * Y[n+k]
Setting up input parameters
in1=[0 1 2 3 4 5 6 7 8 9];
in2=[9 11 12 13 4 5 16 17 18 19];
Cross correlation matlab code without using inbuilt function (xcorr)
Following matlab script is for cross correlation without using inbuilt function such as xcorr.
if length(in1)>length(in2)
pad = length(in1)-length(in2);
in2 = [in2 zeros(1,pad)];
elseif length(in1)<length(in2)
pad = length(in2)-length(in1);
in1 = [in1 zeros(1,pad)];
end
out_len = length(in1);
out = zeros(1,out_len);
tmp = in2;
for k = 1:out_len
out(k) = in1*tmp';
tmp = [0 tmp(1:end-1)];
end
figure;plot(out);title('Our code CORRELATION OUTPUT'); % output plot as per RF Wireless world design of corr function
[m,n]=max(out) % max value in the correlation and its index
Cross correlation matlab code using xcorr
Following matlab script is for cross correlation matlab code using 'xcorr' function.
y=xcorr(in1,in2); % matlab built in function
len=length(y);
index=len/2;
z=y(index:1:end); %extacting one side of the result
figure;plot(z);title('MATLAB xcorr function OUTPUT'); % output plot as per matlab function
[m1,n1]=max(z) % max value in the correlation and its index