note
若要求矩阵的傅里叶变换,则对每个行或列向量求对应的傅里叶变换。
比如matlab中对矩阵求fft傅里叶变换就是对每个列向量分别求傅里叶变换。
code
/*
\brief:离散傅里叶变换
\param dir:变换方向,-1为傅里叶正变换,+1为傅里叶反变换
\param m:个数(向量的维数)
\param real:向量的实部
\param image:向量的虚部
*/
int DFT(int dir, int m, double *real, double *image)
{
if (dir != -1 && dir != 1)
{
return 0;
}
if (m < 1)
{
return 0;
}
if (real == NULL || image == NULL)
{
return 0;
}
long i,k;
double arg;
double cosarg,sinarg;
double *x2 = NULL, *y2 = NULL;
x2 = (double*)malloc(m * sizeof(double)); // 临时数据
y2 = (double*)malloc(m * sizeof(double));
if(x2 == NULL || y2 == NULL)
{
if (x2 != NULL)
{
free(x2);
}
if (y2 != NULL)
{
free(y2);
}
return(0);
}
for(i = 0; i < m; i++)
{
x2[i] = 0;
y2[i] = 0;
arg = dir * 2.0 * 3.141592654 * (double)i / (double)m;
for(k= 0; k < m; k++)
{
cosarg = cos(k * arg);
sinarg = sin(k * arg);
x2[i] += (real[k] * cosarg - image[k] * sinarg);
y2[i] += (real[k] * sinarg + image[k] * cosarg);
}
}
for (i = 0; i < m; i++)
{
if(dir == 1) // 傅里叶逆变换
{
real[i] = x2[i] / (double)m;
image[i] = y2[i] / (double)m;
}
else if (dir == -1) // 傅里叶正变换
{
real[i] = x2[i];
image[i] = y2[i];
}
}
free(x2);
free(y2);
return(1);
}