我正在尝试使用英特尔MKL中名为LAPACKE的LAPACK的C接口来解决一般的带状矩阵。我试图调用的函数是*gbsv
,其中*
表示格式。不幸的是,我发现非常很难找到关于如何使用C接口格式化带状矩阵的工作示例。如果有人可以为所有C用户提供一个工作示例,我向您保证会有所帮助。
fortran布局作为示例here给出,但我不确定如何将其格式化以输入LAPACKE。我还应该注意,在我的问题中,我必须动态构建带状矩阵。所以我有每个i节点有5个系数A,B,C,D,E,它们必须被放入带状矩阵形式,然后传递给LAPACKE。
答案 0 :(得分:2)
函数LAPACKE_dgbsv()
的原型如下:
lapack_int LAPACKE_dgbsv( int matrix_layout, lapack_int n, lapack_int kl,
lapack_int ku, lapack_int nrhs, double* ab,
lapack_int ldab, lapack_int* ipiv, double* b,
lapack_int ldb )
与Lapack函数dgbsv()
的主要区别在于参数matrix_layout
,可以是LAPACK_ROW_MAJOR
(C排序)或LAPACK_COL_MAJOR
(Fortran排序)。如果LAPACK_ROW_MAJOR
,LAPACKE_dgbsv
将转置矩阵,请调用dgbsv()
,然后将矩阵转置回C排序。
其他参数的含义与函数dgbsv()
的含义相同。如果使用LAPACK_ROW_MAJOR
,那么ldab
的正确dgbsv()
将由LAPACKE_dgbsv()
计算,参数ldab
可以设置为n
。但是,就像dgbsv()
一样,必须为矩阵ab
分配额外空间以存储分解的细节。
以下示例利用LAPACKE_dgbsv()
通过居中有限差分来解决一维平台扩散问题。考虑零温度边界条件,并使用正弦波之一作为检查正确性的源项。以下程序由gcc main3.c -o main3 -llapacke -llapack -lblas -Wall
编译:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <lapacke.h>
int main(void){
srand (time(NULL));
//size of the matrix
int n=10;
// number of right-hand size
int nrhs=4;
int ku=2;
int kl=2;
// ldab is larger than the number of bands,
// to store the details of factorization
int ldab = 2*kl+ku+1;
//memory initialization
double *a=malloc(n*ldab*sizeof(double));
if(a==NULL){fprintf(stderr,"malloc failed\n");exit(1);}
double *b=malloc(n*nrhs*sizeof(double));
if(b==NULL){fprintf(stderr,"malloc failed\n");exit(1);}
int *ipiv=malloc(n*sizeof(int));
if(ipiv==NULL){fprintf(stderr,"malloc failed\n");exit(1);}
int i,j;
double fact=1*((n+1.)*(n+1.));
//matrix initialization : the different bands
// are stored in rows kl <= j< 2kl+ku+1
for(i=0;i<n;i++){
a[(0+kl)*n+i]=0;
a[(1+kl)*n+i]=-1*fact;
a[(2+kl)*n+i]=2*fact;
a[(3+kl)*n+i]=-1*fact;
a[(4+kl)*n+i]=0;
//initialize source terms
for(j=0;j<nrhs;j++){
b[i*nrhs+j]=sin(M_PI*(i+1)/(n+1.));
}
}
printf("end ini \n");
int ierr;
// ROW_MAJOR is C order, Lapacke will compute ldab by himself.
ierr=LAPACKE_dgbsv(LAPACK_ROW_MAJOR, n, kl,ku,nrhs, a,n, ipiv, b,nrhs );
if(ierr<0){LAPACKE_xerbla( "LAPACKE_dgbsv", ierr );}
printf("output of LAPACKE_dgbsv\n");
for(i=0;i<n;i++){
for(j=0;j<nrhs;j++){
printf("%g ",b[i*nrhs+j]);
}
printf("\n");
}
//checking correctness
double norm=0;
double diffnorm=0;
for(i=0;i<n;i++){
for(j=0;j<nrhs;j++){
norm+=b[i*nrhs+j]*b[i*nrhs+j];
diffnorm+=(b[i*nrhs+j]-1./(M_PI*M_PI)*sin(M_PI*(i+1)/(n+1.)))*(b[i*nrhs+j]-1./(M_PI*M_PI)*sin(M_PI*(i+1)/(n+1.)));
}
}
printf("analical solution is 1/(PI*PI)*sin(x)\n");
printf("relative difference is %g\n",sqrt(diffnorm/norm));
free(a);
free(b);
free(ipiv);
return 0;
}