MATLAB: Normalized cross-correlation function

signal processing

Hello, i am trying to write a normilized cross-correlation method function , but i can't complete it. Here are the details of the formula :
My code is
x=rand(1,1000);
N=length(x); %// length of signal
n1=128; %// length of window
xf=framing(x,n1,n1/2,rectwin(n1)); %this function frames the signal i will get xf(128,14)
win_num=size(xf,2);
for col=1:win_num
for m=1:n1+1
for n=1:n1-m
ccor(m,col)=sum(xf(n+m,col)*(xf(n,col)))/ sqrt(sum(xf(n)^2)*sum(xf(n+m)^2) );
end
end
end
Note that i want to see the correlation values betwen -1 and 1 like in the figure but instead i get
.

Best Answer

Hi Manolis,
To directly replicate what the equations say (shifting indices with +1), the calculation would look more like this:
x=rand(1,1000);
N=length(x); %// length of signal

n1=128; %// length of window

xf=framing(x,n1,n1/2,rectwin(n1)); %this function frames the signal i will get xf(128,14)

win_num=size(xf,2);
% M0=???

ccor=NaN(M0+1,win_num);
for col=1:win_num
for m=1:M0+1,
[term1,term2,term3]=deal(0);
for n=1:N-m,
term1=term1+xf(n,col)*xf(n+m,col);
term2=term2+xf(n,col)^2;
term3=term3+xf(n+m,col)^2;
end
ccor(m,col)=term1/sqrt(term2*term3);
end
end
You would just need to explicitly specify M0. This calculation can be simplified as follows:
x=rand(1,1000);
N=length(x); %// length of signal
n1=128; %// length of window
xf=framing(x,n1,n1/2,rectwin(n1)); %this function frames the signal i will get xf(128,14)
win_num=size(xf,2);
% M0=???
ccor=NaN(M0+1,win_num);
for col=1:win_num
for m=1:M0+1,
term1=sum(xf(1:N-m,col).*xf(1+m:N,col));
term2=sum(xf(1:N-m,col).^2);
term3=sum(xf(1+m:N,col).^2);
ccor(m,col)=term1/sqrt(term2*term3);
end
end
I don't have the toolbox required to run this code, so it may have bugs. Hope this helps.