用Lapack dgesv求解线性方程组

时间:2012-10-09 10:00:40

标签: c++ linear-algebra lapack equation-solving

我想用C ++中的Lapack软件包解决线性方程组。 我计划使用this中的例程here来实现它,即dgesv。

这是我的代码:

unsigned short int n=profentries.size();
double **A, *b, *x;
A= new double*[n];
b=new double[n];
x=new double[2];
// Generate the matrices for my equation
for(int i = 0; i < n; ++i)
{
    A[i] = new double[2];
}

for(int i=0; i<n; i++)
{
    A[i][0]=5;
    A[i][1]=1;
    b[i]=3;
}

std::cout<< "printing matrix A:"<<std::endl;
for(int i=0; i<n; i++)
{
    std::cout<< A[i][0]<<" " <<A[i][1]<<std::endl;
}
// Call the LAPACK solver
    x = new double[n];//probably not necessary
dgesv(A, b, 2, x); //wrong result for x!
std::cout<< "printing vector x:"<<std::endl;

/*prints 
3
3
but that's wrong, the solution is (0.6, 0)!
*/
for(int i=0; i<2; i++) 
{
    std::cout<< x[i]<<std::endl;
}

我有以下问题:

dgesv如何用元素{3,3}计算向量x?解决方案应该是{0.6,0}(用matlab检查)。

问候

编辑:dgesv可能适用于方形矩阵。我的解决方案展示了如何使用dgels解决超定系统。

2 个答案:

答案 0 :(得分:1)

Lapack假设矩阵以列主格式存储。它不适用于矩阵A的指针指针格式。矩阵的所有元素都需要连续存储在内存中。

尝试声明A:

double *A;
A = new double[2*n];

for-loop:

for(int i=0; i<n; i++)
{
    A[i+0*n]=5;
    A[i+1*n]=1;
    b[i]=3;
}

答案 1 :(得分:1)

问题在于一次是行主要/列主要的混合,而是显然dgesv不适合非方形矩阵的事实。

可以使用dgels(#include“lapacke.h”)以最小二乘方式求解超定线性方程组。

值得注意的是,初看起来并不明显:解决方案向量(通常用x表示)然后存储在b中。

我的示例系统由一个矩阵A和一个向量b组成,矩阵A在第一列中保存值1-10,向量b的值为i ^ 2,用于{i | 1&lt; = i&lt; = 10}:

    double a[10][2]={1,1,2,1,3,1,4,1,5,1,6,1,7,1,8,1,9,1,10,1};
double b[10][1]={1,4,9,16,25,36,49,64,81,100};
lapack_int info,m,n,lda,ldb,nrhs;
int i,j;

// description here: http://www.netlib.org/lapack/double/dgesv.f
m = 10;
n = 2;
nrhs = 1;
lda = 2;
ldb = 1;

for(int i=0; i<m; i++)
{
    for(int k=0; k<lda; k++)
    {
        std::cout << a[i][k]<<" ";
    }
    std::cout <<"" << std::endl;
}
std::cout<< "printing vector b:"<<std::endl;
for(int i=0; i<m; i++) 
{
    std::cout<< *b[i]<<std::endl;
}
std::cout<< "\nStarting calculation..."<<std::endl;

info = LAPACKE_dgels(LAPACK_ROW_MAJOR,'N',m,n,nrhs,*a,lda,*b,ldb);

std::cout<< "Done."<<std::endl;

std::cout<< " "<<std::endl;
std::cout<< "printing vector b:"<<std::endl;
for(int i=0; i<2; i++) 
{
    std::cout<< *b[i]<<std::endl;
}
std::cout<< "Used values: "<< m << ", " <<  n << ", " << nrhs << ", " << lda << ", " << ldb << std::endl;