C语言中编写自定义的互相关函数
代码块
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define NN 10
void xcorr(float *r, unsigned short *x, unsigned short *y, int N);
int main()
{
unsigned short x[10]={1,1,2,2,3,4,5,6,7,8};
unsigned short y[10]={1,3,4,5,6,7,8,9,5,2};
float r[19] = {0};
FILE *fp_out;
int delay;
xcorr(r, x, y, NN);
if((fp_out=fopen("out_xcorr.txt","wt")) == NULL)
{
printf("Cannot open this file!\n");
exit(0);
}
for(delay = -NN + 1; delay < NN; delay++)
fprintf(fp_out,"%d %f\n",delay,r[delay + NN - 1]);
fclose(fp_out);
for(delay = -NN + 1; delay < NN; delay++)
printf("%d %f\n",delay,r[delay + NN - 1]);
system("pause");
return 0;
}
void xcorr(float *r, unsigned short *x, unsigned short *y, int N)
{
float sxy;
int delay,i,j;
for(delay = -N + 1; delay < N; delay++)
{
sxy = 0;
for(i=0; i<N; i++)
{
j = i + delay;
if((j < 0) || (j >= N))
continue;
else
sxy += (x[i] * y[j]);
}
r[delay + N - 1] = sxy;
}
}