Page 1 of 1

Inversing a Dynamic Matrix using dgetri_ and dgetrf_

PostPosted: Mon Mar 07, 2011 12:58 pm
by David12
I am currently trying to inverse a dynamic square (n by n) matrix. The code works for a 2*2 matrix if i specify the elements. However when i tried to make the code work for a dynamic matrix which prompts the user to enter the elements, it crashes. I do not know how dgetri_really works so its proving difficult to solve this problem. Help please!!! Here is my code so far

Code: Select all
#include <stdlib.h>

 void dgetrf_ ( int* m, int* n, double** a, int* lda,int* ipiv, int* info );

 void dgetri_ ( int* n, double**A, int* lda, int* ipiv, double* work, int* lwork, int* info );

  // this inverses the matrix
void inverse (double ** mat, int N)
   int lda, m, info, i, j,lwork;
   int * ipiv;
   double* work;
   lda = N;
   m = N;
   lwork = 100*N;

   ipiv = (int*)malloc(20*N*sizeof(int));
   work = (double*)malloc(10*N*N*(sizeof(double)));
   dgetrf_ ( &N, &N, mat, &lda,ipiv,&info );
   printf ("Matrix  after dgetrf\n");
    for (i=0;i<N;i++) {
      for (j=0;j<N;j++)
        printf ("A[%d][%d]:%f\t", i,j,mat[i][j]);
    printf ("\ninfo for dgetrf_:%d\n\n", info);
   printf ("Matrix  after dgetri\n");
    for (i=0;i<N;i++) {
      for (j=0;j<N;j++)
        printf ("A[%d][%d]:%f\t", i,j,mat[i][j]);
   printf ("\ninfo for dgetri_:%d\n\n", info);
   free (work);

// this allocates memory to the dynamic matrix
double** allomat (int row, int col)

double **matrix;
int i;
matrix = (double **) malloc (row*sizeof(double *));
if (!matrix) return NULL; /* failed */
matrix[0] = (double *) malloc (row*col*sizeof(double));
if (!matrix[0])
free(matrix); /* we don’t need matrix any more */
return NULL; /* failed */
for (i = 1; i < row; i++)
matrix[i] = matrix[i-1] + col;
return matrix;

void printmat (double** mat, int row, int col)
   int i,j;
   for (i=0; i< row; i++)
      for (j=0; j< col; j++)
         printf ("%9.3lf", mat [i][j]);
int main()
   int i,j,n;
   double **matA;
   printf("enter rows = column\n");
   scanf (" %d",&n);
   matA = allomat(n,n);
   if (!matA)
   { printf("error in malloc\n");
     return -1;
   printf("enter elements\n");
   //printf ("i,j,n%d %d %d\n", i,j,n);
   for (i=0;i < n; i++){
      { scanf("%lf",&matA[i][j]);
   printmat (matA,n,n);
   //printmat (matA,n,n);
   return 0;