不知道有没有人可以把我引用到ANSI C中的1D线性
convolution代码片段?我在谷歌搜索和堆栈溢出,但找不到任何东西在C我可以使用.
例如,对于阵列A,B和C,分别输出A和B为输入和C的所有双精度,分别具有长度len_A,len_B和len_C = len_A len_B-1.
解决方法
就是这样:
#include <stddef.h> #include <stdio.h> void convolve(const double Signal[/* SignalLen */],size_t SignalLen,const double Kernel[/* KernelLen */],size_t KernelLen,double Result[/* SignalLen + KernelLen - 1 */]) { size_t n; for (n = 0; n < SignalLen + KernelLen - 1; n++) { size_t kmin,kmax,k; Result[n] = 0; kmin = (n >= KernelLen - 1) ? n - (KernelLen - 1) : 0; kmax = (n < SignalLen - 1) ? n : SignalLen - 1; for (k = kmin; k <= kmax; k++) { Result[n] += Signal[k] * Kernel[n - k]; } } } void printSignal(const char* Name,double Signal[/* SignalLen */],size_t SignalLen) { size_t i; for (i = 0; i < SignalLen; i++) { printf("%s[%zu] = %f\n",Name,i,Signal[i]); } printf("\n"); } #define ELEMENT_COUNT(X) (sizeof(X) / sizeof((X)[0])) int main(void) { double signal[] = { 1,1,1 }; double kernel[] = { 1,1 }; double result[ELEMENT_COUNT(signal) + ELEMENT_COUNT(kernel) - 1]; convolve(signal,ELEMENT_COUNT(signal),kernel,ELEMENT_COUNT(kernel),result); printSignal("signal",signal,ELEMENT_COUNT(signal)); printSignal("kernel",ELEMENT_COUNT(kernel)); printSignal("result",result,ELEMENT_COUNT(result)); return 0; }
输出:
signal[0] = 1.000000 signal[1] = 1.000000 signal[2] = 1.000000 signal[3] = 1.000000 signal[4] = 1.000000 kernel[0] = 1.000000 kernel[1] = 1.000000 kernel[2] = 1.000000 kernel[3] = 1.000000 kernel[4] = 1.000000 result[0] = 1.000000 result[1] = 2.000000 result[2] = 3.000000 result[3] = 4.000000 result[4] = 5.000000 result[5] = 4.000000 result[6] = 3.000000 result[7] = 2.000000 result[8] = 1.000000