这个是很简单,但是真写出来也写了半天
保留着看自己以后会不会用到
卷积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)
.
.
.
.
.
#include
using namespace std;
float min(float a, float b)
{
return a < b ? a : b;
}
void convolution(float *input1, float *input2, float *output, int mm, int nn)
{
float *xx = new float[mm + nn - 1];
float *tempinput2 = new float[mm + nn - 1];
for (int i = 0; i < nn; i++)
{
tempinput2[i] = input2[i];
}
for (int i = nn; i < mm + nn - 1; i++)
{
tempinput2[i] = 0.0;
}
// do convolution
for (int i = 0; i < mm + nn - 1; i++)
{
xx[i] = 0.0;
int tem = (min(i, mm)) == mm ? mm-1 : min(i, mm);
for (int j = 0; j <= tem; j++)
{
xx[i] += (input1[j] * tempinput2[i - j]);
}
}
// set value to the output array
for (int i = 0; i < mm+nn-1; i++)
output[i] = xx[i];
delete [] tempinput2 ;
delete[] xx;
}
int main()
{
float a[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
float b[4] = { 1, 2, 3, 4 };
float *c = new float[9];
convolution(a, b, c, 9, 4);
for (int i = 0; i < 13; i++)
{
cout << c[i] << " ";
}
getchar();
return 0;
}
matlab 结果如下