// filename:QR_test.c
// author: xiaogu
// date: 2010-12-23
#include"QR_test.h"
int main(int argc, char * argv[])
{
int N;//矩阵的大小N*N,本程序中必须为方阵
float *matA,*matR,*matQ;
float time_start,time_end;
int mode = CheckPara(argc,argv);//参数检测
switch(mode)
{
case 0://参数错误
return 0;
case 1://使用了参数‘-r’,即随机生成矩阵
sscanf(argv[2],"%d",&N);
matA=(float*)malloc(sizeof(float)*N*N);
GetRandomMatrix(matA,N);
break;
case 2://使用了参数'-f',即从文件读取矩阵
N=GetNFromFile();
matA=(float*)malloc(sizeof(float)*N*N);
GetMatFromFile(matA);
break;
default://其他
return 0;
}
//QR分解
time_start = 1.0*clock()/CLOCKS_PER_SEC;
matQ=(float*)malloc(sizeof(float)*N*N);
matR=(float*)malloc(sizeof(float)*N*N);
MatrixQR(matA,matQ,matR,N);//矩阵QR分解函数
time_end = 1.0*clock()/CLOCKS_PER_SEC;
//现实信息
DisplayMatrix(matA,N,"Matrix Origin:");
DisplayMatrix(matR,N,"Matrix R:");
TransposeMatrix(matQ,N);//对矩阵Q进行转置
DisplayMatrix(matQ,N,"Matrix Q:");
printf("Time used:%.2fs\n ",time_end-time_start);//计算QR分解时间
free(matA);
free(matR);
free(matQ);
return 0;
}
//获取随机矩阵
void GetRandomMatrix(float *mat,int N)
{
int i,len=N*N;
srand((unsigned) time(NULL));
for(i=0;i<len;i++)mat[i]=(rand()%65535)/6553.5-2;
}
int GetNFromFile()
{
int M,N;
FILE *fdA;
fdA=fopen("dataIn.txt","r");
fscanf(fdA,"%d %d", &M, &N);
if(M != N)//矩阵不为方阵
{
printf("The input is error!\n");
exit(0);
}
fclose(fdA);
return N;//返回矩阵大小
}
//从文件读取矩阵
void GetMatFromFile(float *mat)
{
int M,N,i,j;
FILE *fdA;
fdA=fopen("dataIn.txt","r");
fscanf(fdA,"%d %d", &M, &N);
if(M != N)//矩阵不为方阵
{
printf("The input is error!\n");
exit(0);
}
for( i = 0; i < N; i ++)
{
for( j = 0; j < N; j ++)
{
fscanf(fdA, "%f",mat+i*N+j);
}
}
fclose(fdA);
}
//生成单位矩阵
void CreateIMatrix(float *mat,int N)
{
int i,j;
for(i=0;i<N;i++)
for(j=0;j<N;j++)
{
if (i==j)
mat(i,j)=1.0;
else
mat(i,j)=0.0;
}
}
//显示矩阵
void DisplayMatrix(float *mat,int N,const char * strTitle)
{
int i,j;
printf("%s\n",strTitle);//打印标题
if(N>10)
{
printf("\tThe matrix is too large to show!\n\n");
return;
}
for(i=0;i<N;i++)//打印矩阵
{
for(j=0;j<N;j++)printf("%10.2f",*mat++);
printf("\n");
}
printf("\n");
}
//对矩阵进行转置
void TransposeMatrix(float *mat,int N)
{
int i,j;
float temp;
for(i=0;i<N;i++)
for(j=i+1;j<N;j++)
{
temp=mat(i,j);
mat(i,j)=mat(j,i);
mat(j,i)=temp;
}
}
//检测参数
int CheckPara(int argc, char *argv[])
{
if(argc <2 || argc >3)
{
ShowHelp();
return 0;//参数个数错误
}
if(strcmp(argv[1],"-r")==0)
{
if(argc != 3)
{
ShowHelp();
return 0;
}
return 1;
}
else if(strcmp(argv[1],"-f")==0)
{
if(argc != 2)
{
ShowHelp();
return 0;
}
return 2;
}
else
{
ShowHelp();
return 0;
}
}
//现实使用提示
void ShowHelp()
{
printf("use \"-f\" or \"-r x\"!\n");
printf(" -f: get matrix from dataIn.txt.\n");
printf(" -r: generate random matrix.\n x: rows of matrix\n");
}