Search code examples
matlabsignalscorrelationautocorrelation

Autocorrelation function in matlab without using built-in function


I am trying to write a code for the colculate autocorrelation function. Could you suggest what I'm doing wrong. Thanks in advance

 i = 1:199;
    U =sin(0.3*i);
    sum_1 = 0;
    for tau = 1:length(U)
       for   t = tau:length(U)-1
           
             sum_1 = sum_1+sum(U(t).*U(t+1-tau));
             r(tau)=sum_1;
        end
    end

Solution

  • You can do something like this. This is an implementation of the original algorithm with only a small optimization; calculating half the sequence and copying the remaining half.

    n = length(x);
    m = 2*n - 1;
    rxx = zeros(1,m);
    for i = 1:length(x)
        rxx(i) = dot(x(n-i+1:n), x(1:i).');
        rxx(m-i+1) = rxx(i)';
    end
    

    Example:

    x = [2, 3, -1];
    
    rxx =
        -2     3    14     3    -2
    
    % MATLAB built-in
    xcorr(x,x)
    ans =
        -2     3    14     3    -2