write a cross corellation algorithm in matlab

Here's a MATLAB implementation of the cross-correlation algorithm using matrix multiplication:

main.m
function [xcorr, lag] = myxcorr(x, y)
% MYXCORR: Compute the cross-correlation of two signals
%   xcorr = myxcorr(x, y) returns the cross-correlation of two signals x and y
%   lag is the vector of lags in samples

N = length(x);
M = length(y);
% Zero-pad the shorter signal to match the length of the longer signal
if N < M
    x(N+1:M) = 0;
else
    y(M+1:N) = 0;
end
% Compute the cross-correlation using matrix multiplication
xcorr = ifft(fft(x) .* conj(fft(y)));
% Compute the lags in samples
lags = -(N-1):(N-1);
% Normalize the cross-correlation by the maximum value
xcorr = xcorr / max(xcorr);
% Return only the positive lags
xcorr = xcorr(N:end);
lags = lags(N:end);
% Plot the cross-correlation
stem(lags, xcorr);
xlabel('Lag (samples)');
ylabel('Normalized cross-correlation');
789 chars
27 lines

To use this function, simply call myxcorr(x, y), where x and y are the two signals to compute the cross-correlation of. The function will return two outputs: xcorr is the cross-correlation vector and lag is the vector of lags in samples. The function will also plot the cross-correlation using stem. Note that in order to make the cross-correlation symmetric around zero lag, we zero-pad the shorter signal to match the length of the longer signal.

gistlibby LogSnag