function corr = corrfn(x,y, k)

sample = find (all (~isnan([y,x]),2));

xx =x -mean(x(sample));
yy =y -mean(y(sample));

M = [xx(sample), yy(sample)];
aux = M' * M;
s = sqrt(aux(1,1)* aux(2,2));

zero_corr = aux(1,2) / s;

lag_corr = zeros([k,1]);
lead_corr = zeros([k,1]);

for m =1:k
    subsample = sample(1+m:end);
    
    M = [xx(subsample), yy(subsample-m)];
    aux = M' * M;
    lag_corr(m,1) = aux(1,2) /s;
    
    M = [xx(subsample-m), yy(subsample)];
    aux = M' * M;
    lead_corr(m,1) = aux(1,2) /s;
end

corr = [lead_corr(end:-1:1); zero_corr; lag_corr];

return
    

    
    