上一篇的源码进行优化,将cosx运算提取出来,变成矩阵形式。
#include "stdafx.h"
#include <string.h>
#include <iostream>
#include <math.h>
using namespace std;
#define PI 3.1415926
int _tmain(int argc, _TCHAR* argv[])
{
double dInput[] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
int iFactor[] = {1, 1, 1, 1, 0, 0, 0, 0, 0, 0};
double dOut[10] = {0};
double dOut1[10]= {0};
const int N = sizeof(dInput)/sizeof(double);
double* pdFactor = new double[N*N];
for (int row=0; row<N; row++)
{
for (int col=0; col<N; col++)
{
if (row==0)
pdFactor[row*N+col] = cos((2*col + 1)*PI*row/(2*N)) / sqrt((double)N);
else
pdFactor[row*N+col] = cos((2*col + 1)*PI*row/(2*N)) * sqrt(2.0) / sqrt((double)N);
}
}
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
dOut[i]+= dInput[j] * pdFactor[i*N+j];
}
}
printf("\n变换前:\n");
for (int i=0; i<N; i++)
{
printf("%f\t", dInput[i]);
}
printf("\n变换后:\n");
for (int i=0; i<N; i++)
{
printf("%f\t", dOut[i]);
}
//printf("\n去除高频:\n");
//for (int i=0; i<N; i++)
//{
// dOut[i] *= iFactor[i];
// printf("%f\t", dOut[i]);
//}
printf("\n逆变换:\n");
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
dOut1[i]+= dOut[j] * pdFactor[j*N+i];
}
}
for (int i=0; i<N; i++)
{
printf("%f\t", dOut1[i]);
}
getchar();
delete[] pdFactor;
}
#include <string.h>
#include <iostream>
#include <math.h>
using namespace std;
#define PI 3.1415926
int _tmain(int argc, _TCHAR* argv[])
{
double dInput[] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
int iFactor[] = {1, 1, 1, 1, 0, 0, 0, 0, 0, 0};
double dOut[10] = {0};
double dOut1[10]= {0};
const int N = sizeof(dInput)/sizeof(double);
double* pdFactor = new double[N*N];
for (int row=0; row<N; row++)
{
for (int col=0; col<N; col++)
{
if (row==0)
pdFactor[row*N+col] = cos((2*col + 1)*PI*row/(2*N)) / sqrt((double)N);
else
pdFactor[row*N+col] = cos((2*col + 1)*PI*row/(2*N)) * sqrt(2.0) / sqrt((double)N);
}
}
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
dOut[i]+= dInput[j] * pdFactor[i*N+j];
}
}
printf("\n变换前:\n");
for (int i=0; i<N; i++)
{
printf("%f\t", dInput[i]);
}
printf("\n变换后:\n");
for (int i=0; i<N; i++)
{
printf("%f\t", dOut[i]);
}
//printf("\n去除高频:\n");
//for (int i=0; i<N; i++)
//{
// dOut[i] *= iFactor[i];
// printf("%f\t", dOut[i]);
//}
printf("\n逆变换:\n");
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
dOut1[i]+= dOut[j] * pdFactor[j*N+i];
}
}
for (int i=0; i<N; i++)
{
printf("%f\t", dOut1[i]);
}
getchar();
delete[] pdFactor;
}
由此源码发现。
参数因子pdFactor,由编码的逐行积相加,变为解码的逐列的积相加。