Implementing cross correlation in Matlab without using xcorr

If you’ve ever wanted to implement the cross correlation function in Matlab without using the inbuilt xcorr function, this post might be of some help for you.

This is how such a function could look like:

%Implementation of the cross correlation function
function [result] = crossCorrelation(signalA,signalB)
  signalALength = size(signalA,1);
  signalBLength = size(signalB,1);

  result = zeros(1, signalALength + signalBLength - 1 );
  resultLength = size(result,2);

  for m = 1 : resultLength
    arg = (m - signalALength);

    if(arg < 0)
      negativeCondition = 1;
      limit = signalALength + arg;
    else
      negativeCondition = 0;
      limit = signalALength - arg;
    end

    for n = 1:limit
      if (negativeCondition)
        result(m) = result(m) + signalA(n) * signalB(n - arg);
      else
        result(m) = result(m) + signalA(arg + n) * signalB(n);
      end
    end
  end
end

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s