2

I am currently in the process of converting a MATLAB algorithm to C in order to use it in an iOS application.

I've been struggling with the MATLAB's xcorr function. Here is the relevant MATLAB code.

xcr = xcorr(A,A,maxlags);

This , according to MATLAB documentation

returns the cross-correlation sequence over the lag range [-maxlags:maxlags]. Output c has length 2*maxlags+1.

The Apple Accelerate.Framework provides a convolution/correlation function named vDSP_conv but I fail to see how to use it in a way that it produces the same output as xcorr. Is this possible ? If yes could anyone help me.

Best Regards,

Acacio

Acacio Martins
  • 155
  • 2
  • 10
  • Perhaps looking at GNU Octave's implementation would help- they implement it http://octave.sourceforge.net/signal/function/xcorr.html – joerick Dec 10 '12 at 16:11
  • 1
    See: http://stackoverflow.com/questions/10917951/perform-autocorrelation-with-vdsp-conv-from-apple-accelerate-framework – Pete Dec 10 '12 at 19:00
  • If the question pointed to by Pete does not resolve the problem for you, then please post the result of MATLAB’s xcorr when `A` is `[1, 2, 3]` and `maxlags` is 3, or another small example. That may display details of the function that help match it to `vDSP_conv` behavior. – Eric Postpischil Dec 10 '12 at 19:53
  • Hello, the result is [0,3,8,14,8,3,0]. I've run it with maxlags = 2 and got [3,8,14,8,3]. I also tried it with A = [1,2,3,4,5,6,7] and maxlags = 3 and got [60,85,112,140,112,85,60]. Thanks for your help. – Acacio Martins Dec 11 '12 at 10:56

1 Answers1

4

To duplicate the results of MATLAB’s xcorr, you need to pad the vector with zeroes before and after:

#include <stdio.h>

#include <Accelerate/Accelerate.h>


int main(void)
{
    #define NF  3
    #define NC  (2*NF+1)

    float A[3*NF] = {0, 0, 0, 1, 2, 3, 0, 0, 0};
    float C[NC];

    vDSP_conv(A, 1, A+NF, 1, C, 1, NC, NF);

    for (vDSP_Length i = 0; i < NC; ++i)
        printf("C[%u] = %g.\n", (unsigned) i, C[i]);

    return 0;
}
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312