簡體   English   中英

LAPACKE矩陣求逆分段錯誤C

[英]LAPACKE matrix inversion segmentation fault C

我正在嘗試使用 lapacke 庫編寫代碼來反轉 C 中的復雜矩陣。但是我遇到了分段錯誤,這似乎取決於矩陣的大小 N。 更重要的是,每次編譯程序或觸摸任何東西時,發生分段錯誤的大小都會有所不同。 這讓我覺得某處代碼試圖訪問分配不當或禁止的內存。 不幸的是,我不明白這是如何發生的,因為它似乎與 LAPACKE 函數本身有關。 事實上,當函數 / *MatrixComplexInv(invA,A,N);*/ (其中調用 LAPACKE 函數進行反演)被注釋時,分段錯誤不會發生。 下面是可以自己編譯和運行的工作代碼。

 #include <stdio.h>
#include <lapacke.h>
#include <complex.h>
#include <stdlib.h>
#include <math.h>

void  Ctranspose( double complex *, double complex * ,int );
void MatrixComplexInv(double complex *, double complex *, int );


int main(int argc,  const char * * argv) {


 int  i,j,k,N = 4;/*if N> bigger than a small number 4,6,7.. it gives segmentation fault*/

double complex *A = calloc(N*N,sizeof(double complex)),
               *b = calloc(N*N,sizeof(double complex)),
               *Ap =calloc(N*N,sizeof(double complex));


    double complex *invA =calloc(N*N,sizeof(double complex));


        for(i=0;i<N;i++){
            for(j=0;j<N;j++){ 

            A[i*N+j] = 1+sin(i*j)*i+I*j;    
            Ap[i*N+j] = 1+sin(i*j)*i+I*j;   
            }
          }

    /*Segmentation fault in this function, due to 
     * 
    LAPACKE_zgetrf(LAPACK_ROW_MAJOR, n, n, tempA , n,&n);


    LAPACKE_zgetri(LAPACK_ROW_MAJOR, n, tempA , n, &n );
    * 
    * both.
    */
    MatrixComplexInv(invA,A,N);


    for(i=0;i<N;i++){
     for(j=0;j<N;j++){ 
         for(k = 0;k<N;k++){
            b[i*N+j]+=invA[i*N + k]*Ap[k*N + j];
         }


   printf("(%lf,%lf)\t", creal(b[i*N + j]),cimag(b[i*N + j]));/*tests that the result produces the inverse matrix A^{-1}A = 1*/


    }
     printf("\n");
    }

      return 0;
    }   


    void Ctranspose( double complex *Transposed, double complex *M ,int n)
    {

    int i,j;
    for(i=0;i<n;i++)

    for(j=0;j<n;j++) Transposed[i+n*j] = M[i*n+j];
    }


    void MatrixComplexInv(double complex *invA, double complex *A, int n)
    {

    double complex *tempA = (double complex*) malloc( n*n*sizeof(double complex) );


     Ctranspose(tempA,A,n);

    /*SEGMENTATION HAPPEN IN THESE TWO FUNCTIONS*/
    LAPACKE_zgetrf(LAPACK_ROW_MAJOR, n, n, tempA , n,&n);


    LAPACKE_zgetri(LAPACK_ROW_MAJOR, n, tempA , n, &n );


     Ctranspose(invA,tempA,n);


     free(tempA);

    }

LAPACKE_zgetrf(LAPACK_ROW_MAJOR, n, n, tempA , n,&n); , LAPACKE_zgetrf的最后一個參數指向 n,一個整數。 相反,參數ipiv應該是 一個指向維度為 max(m,n) 的整數數組的指針,以存儲樞軸索引這可以解釋分段錯誤。

所述ipiv通過計算LAPACKE_zgetrf()也必須被提供給LAPACKE_zgetri()作為輸入,以獲得正確的逆矩陣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM