一维卷积c实现

来源:互联网 发布:格式化成json字符串 编辑:程序博客网 时间:2024/04/30 03:12

卷积Y(n)=x(n)*h(n)

=∑x(i)h(n-i);

举个例子

简单点

x(n)={1,2,3,4};h(n)=(1,2,3,4);



y(0)=x(0)h(0);

y(1)=x(0)h(1)+x(1)h(0)

y(2)=x(0)h(2)+x(1)h(1)+x(2)h(0);

y(3)=x(0)h(3)+x(1)h(2)+x(2)h(1)+x(3)h(0);

y(4)=x(0)h(4)+x(1)h(3)+x(2)h(2)+x(3)h(1)

.

.

.

.

.



[cpp] view plain copy
  1. #include <iostream>  
  2.   
  3. using namespace std;  
  4. float min(float a, float b)  
  5. {  
  6.     return a < b ? a : b;  
  7. }  
  8. void convolution(float *input1, float *input2, float *output, int mm, int nn)  
  9. {  
  10.     float *xx = new float[mm + nn - 1];  
  11.     float *tempinput2 = new float[mm + nn - 1];  
  12.     for (int i = 0; i < nn; i++)  
  13.     {  
  14.         tempinput2[i] = input2[i];  
  15.     }  
  16.     for (int i = nn; i < mm + nn - 1; i++)  
  17.     {  
  18.         tempinput2[i] = 0.0;  
  19.     }  
  20.     // do convolution   
  21.     for (int i = 0; i < mm + nn - 1; i++)  
  22.     {  
  23.         xx[i] = 0.0;  
  24.         int tem = (min(i, mm)) == mm ? mm-1 : min(i, mm);  
  25.         for (int j = 0; j <= tem; j++)  
  26.         {  
  27.             xx[i] += (input1[j] * tempinput2[i - j]);  
  28.         }   
  29.     }  
  30.     // set value to the output array   
  31.     for (int i = 0; i < mm+nn-1; i++)  
  32.         output[i] = xx[i];  
[cpp] view plain copy
  1. <span style="white-space:pre">    </span>delete [] <span style="font-family: Arial, Helvetica, sans-serif;">tempinput2 ;</span>  
  2.     delete[] xx;  
  3. }  
  4.   
  5. int main()  
  6. {  
  7.     float a[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };  
  8.     float b[4] = { 1, 2, 3, 4 };  
  9.     float *c = new float[9];  
  10.     convolution(a, b, c, 9, 4);  
  11.     for (int i = 0; i < 13; i++)  
  12.     {  
  13.         cout << c[i] << " ";  
  14.     }  
  15.     getchar();  
  16.     return 0;  
  17. }  



matlab 结果如下

0 0
原创粉丝点击