C program to find Inverse of Matrix

Mr Coder September 17, 2012 17

C program to find Inverse of Matrix : For a square matrix A, the inverse matrix is written A-1. When A is multiplied by A-1 the result is the identity matrix I. Non-square matrices do not have inverses. There are several different methods for calculating inverse of Matrix like Augmented Matrix Method, Adjoint Method and few shortcut methods. Today i have written a  C program to find Inverse of Square or say NxN Matrix using Adjoint Method.

Note: Not all square matrices have inverses. A square matrix which has an inverse is called invertible or non-singular, and a square matrix without an inverse is called non-invertible or singular.

Algorithm to calculate Inverse of Matrix using Adjoint Method :

1) calculating the Matrix of Minors

2) then turn that into the Matrix of Cofactors

3) then the Adjugate

4) multiply that by 1/Determinant.

But it is best explained by working through an example!

Example: find the Inverse of A:

Inverse of Matrix Image 1

It needs 4 steps. It is all simple arithmetic but there is a lot of it, so try not to make a mistake!

Step 1: Matrix of Minors

The first step is to create a “Matrix of Minors”:

For each element of the matrix:

  • ignore the values on the current row and column
  • calculate the determinant of the remaining values

Put those determinants into a matrix (the “Matrix of Minors”)

Determinants

For a 2×2 matrix (2 rows and 2 columns) the determinant is easy: ad-bc

Think of a cross:

  • Blue means positive (+ad),
  • Red means negative (-bc)
A Matrix

The Calculations

Here are the first two, and last two, calculations of the “Matrix of Minors” (notice how I ignore the values in the current row and columns, and calculate the determinant using the remaining values):

Inverse of Matrix Image 2

And here is the calculation for the whole matrix:

Inverse of Matrix Image 3

Step 2: Matrix of Cofactors

This is easy! Just apply a “checkerboard” of minuses to the “Matrix of Minors”. In other words, you need to change the sign of alternate cells, like this:

Step 3: Adjugate (also called Adjoint)

Now “Transpose” all elements of the previous matrix… in other words swap their positions over the diagonal (the diagonal stays the same):

Inverse of Matrix Image 4

Step 4: Multiply by 1/Determinant

Now find the determinant of the original matrix. This isn’t too hard, because we already calculated the determinants of the smaller parts when we did “Matrix of Minors”.

A Matrix

So: multiply the top row elements by their matching “minor” determinants:

Determinant = 3×2 – 0×2 + 2×2 = 10

And now multiply the Adjugate by 1/Determinant:

Inverse of Matrix Image 6

And we are done!

 

Now let us see how to implement above explained method using C program which takes order of Square Matrix as input and then Matrix and displays Determinant and Inverse Matrix as output.

C Program to find Inverse of Matrix :

#include<stdio.h>
#include<math.h>
#include<conio.h>
float determinant(float[][],float);
void cofactor(float[][],float);
void transpose(float[][],float[][],float);
int main()
{
  float a[25][25],k,d;
  int i,j;
  printf("-------------------------------------------------------------\n");
  printf("----------------made by C code champ ------------------------\n");
  printf("-------------------------------------------------------------\n");
  printf("\n  C Program to find inverse of Matrix\n\n"); 
  printf("Enter the order of the Matrix : ");
  scanf("%f",&k);
  printf("Enter the elements of %.0fX%.0f Matrix : \n",k,k);
  for (i=0;i<k;i++)
    {
     for (j=0;j<k;j++)
       {
        scanf("%f",&a[i][j]);
        }
    }
  d=determinant(a,k);
  printf("Determinant of the Matrix = %f",d);
  if (d==0)
   printf("\nInverse of Entered Matrix is not possible\n");
  else
   cofactor(a,k); 
   printf("\n\n**** Thanks for using the program!!! ****");
   getch();
}

/*For calculating Determinant of the Matrix */
float determinant(float a[25][25],float k)
{
  float s=1,det=0,b[25][25];
  int i,j,m,n,c;
  if (k==1)
    {
     return (a[0][0]);
    }
  else
    {
     det=0;
     for (c=0;c<k;c++)
       {
        m=0;
        n=0;
        for (i=0;i<k;i++)
          {
            for (j=0;j<k;j++)
              {
                b[i][j]=0;
                if (i != 0 && j != c)
                 {
                   b[m][n]=a[i][j];
                   if (n<(k-2))
                    n++;
                   else
                    {
                     n=0;
                     m++;
                     }
                   }
               }
             }
          det=det + s * (a[0][c] * determinant(b,k-1));
          s=-1 * s;
          }
    }

    return (det);
}

void cofactor(float num[25][25],float f)
{
 float b[25][25],fac[25][25];
 int p,q,m,n,i,j;
 for (q=0;q<f;q++)
 {
   for (p=0;p<f;p++)
    {
     m=0;
     n=0;
     for (i=0;i<f;i++)
     {
       for (j=0;j<f;j++)
        {
          if (i != q && j != p)
          {
            b[m][n]=num[i][j];
            if (n<(f-2))
             n++;
            else
             {
               n=0;
               m++;
               }
            }
        }
      }
      fac[q][p]=pow(-1,q + p) * determinant(b,f-1);
    }
  }
  transpose(num,fac,f);
}
/*Finding transpose of matrix*/  
void transpose(float num[25][25],float fac[25][25],float r)
{
  int i,j;
  float b[25][25],inverse[25][25],d;

  for (i=0;i<r;i++)
    {
     for (j=0;j<r;j++)
       {
         b[i][j]=fac[j][i];
        }
    }
  d=determinant(num,r);
  for (i=0;i<r;i++)
    {
     for (j=0;j<r;j++)
       {
        inverse[i][j]=b[i][j] / d;
        }
    }
   printf("\n\n\nThe inverse of matrix is : \n");

   for (i=0;i<r;i++)
    {
     for (j=0;j<r;j++)
       {
         printf("\t%f",inverse[i][j]);
        }
    printf("\n");
     }
}

We hope you all have enjoyed the article on C program to find Inverse of NxN Matrix. If you have any issues ask me in form of comments.

References:

1. Mathwords 

2. Mathisfun(Example)

3. Inverse of Square Matrix

4. Wikipedia

17 Comments »

  1. TJ October 16, 2012 at 8:45 am - Reply

    Well written! It really helped out with my assignment! Many thanks and bravo!

  2. TJ October 16, 2012 at 8:45 am - Reply

    Well written! It really helped out with my assignment! Many thanks and bravo!

  3. Matthew R Giese October 17, 2012 at 7:46 am - Reply

    I’ve a WordPress blog with Arras theme. This site strangely shows different on different computers. On some computers, I see all 3 columsn, on other PC, I see only 1. On other PCs, some wiered things. Please somebody help me..

  4. Francesco Banda Jasso October 26, 2012 at 10:06 pm - Reply

    Where can I find the best online creative writing courses? I live in NYC so which colleges offer the best online creative writing course? If not in a college than where else?.

  5. Canada Goose November 1, 2012 at 1:34 pm - Reply

    There are only 27 nations of earth with GDP greater than that number.

  6. Mark November 2, 2012 at 3:37 pm - Reply

    Having a good product is one of the best marketing strategies, this is so simple and so true! Thanks for the post.

  7. baju bayi baru lahir November 5, 2012 at 6:26 am - Reply

    Wow, wonderful blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is fantastic, let alone the content!. Thanks For Your article about C Program to find inverse of matrix | Inverse of NxN Matrix .

  8. Karolyn Feggins November 6, 2012 at 4:16 pm - Reply

    Saved as a favorite, I like your website!

  9. behnam November 27, 2012 at 5:33 pm - Reply

    Thank you so much
    I need it to Pascal
    Please help

  10. emenent January 7, 2013 at 4:13 am - Reply

    sir i like the code since its nt too long nd works… but i will feel more comfortable if u add comments to make understand wht actually is happening in each n every line….

    regards

  11. Achchuthan January 28, 2013 at 3:59 am - Reply

    full of error n ur program.please correct an post it again with output.
    anyway thank you

    • Mr Coder January 31, 2013 at 1:10 pm - Reply

      Its perfectly correct and working fine. Please copy the code correctly and execute it with the help of Dev C++ compiler or Code blocks.

  12. dodylee February 7, 2013 at 7:18 pm - Reply

    The code is very difficult and solving of determinant of matrix can by written with recursion techniques (except other parts of code). Its looks like beginners programming trying.

  13. Nayeem Bin Ahsan March 26, 2013 at 5:01 pm - Reply

    this program 100% correct .
    please fill up blank [] with 25 .
    as like ……………….

    #include
    #include
    #include
    float determinant(float[25][25],float);
    void cofactor(float[25][25],float);
    void transpose(float[25][25],float[25][25],float);
    int main()
    {………………………………………………………………………………..

    Tnx bro ,
    solve this problem . I am new in c . A lot of good wish for U .

  14. Mr BMSRAO April 1, 2013 at 6:19 am - Reply

    The programme in c about inverse of nxn matrix is not compiled when tested what could be the reason ?
    bmsrao

  15. Tiny Sarvey August 27, 2013 at 12:30 pm - Reply

    Wow, amazing blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is excellent, let alone the content!. Thanks For Your article about C Program to find inverse of matrix | Inverse of NxN Matrix .

Leave A Response »