Skip to content

Instantly share code, notes, and snippets.

@ferryzhou
Created April 16, 2012 14:50
Show Gist options
  • Save ferryzhou/2399236 to your computer and use it in GitHub Desktop.
Save ferryzhou/2399236 to your computer and use it in GitHub Desktop.
Align two signals using correlation
function [ao, bo, offset, y] = align(a, b)
% align two signals a and b
% ao and bo are aligned ones with same length
% y is the correlation xcorr(a, b)
% a_ind + offset -> b_ind
% if offset >= 0, cut a, else cut b
an = length(a); bn = length(b);
N = max(an, bn);
y = xcorr(a, b);
% y(i) = Rxy(i-N) -> a(n+i-N) ~ b(n) if i >=N,
% y(i) = Ryx(N-i) -> b(n+N-i) ~ a(n) if i < N
[yy, ii] = max(y);
offset = ii - N;
if offset >= 0 % offset for a: ii - N
ao = a(offset + 1 : end);
if (length(ao) > bn), bo = b; ao = ao(1:bn);
else bo = b(1:length(ao)); end
else % offset for b: N - ii
bo = b(-offset + 1 : end);
if (length(bo) > an)
ao = a; bo = bo(1:an);
else
ao = a(1:length(bo));
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment