Saturday 9 December 2017

HOW TO FIND INVERSE OF A MATRIX USING C++?

INVERSE OF A MATRIX

This post is for CLASS 12 Students. Are you bored to find Determinant, Cofactor, Adjoint and Finally Inverse ?



What if you type the question and all the above things come directly on your computer screen.

First I will say how did i do this?

  •     Know the normal way
  •     Find the shortcut. Here I used a Shortcut.
  •     Write down Algorithm.
  •     Now Start Coding.
  •     You should be focussed on your output.
  •     Combine Maths and C++
  •     That's it. You did it.

Here is a sample.


Or what if Determinant is ZERO.Check this


What NEXT?..........CODE. Copy and paste it in your Notepad and change it into .cpp. Here is the code.

  1. #include<iostream.h>
  2. #include<conio.h>
  3. void get(int a[3][3])
  4. {
  5.  for(int i=0;i<3;i++)
  6.  {
  7.   for(int j=0;j<3;j++)
  8.   {
  9.    cout<<"Enter the value of...a["<<i+1<<"]["<<j+1<<"]....";
  10.    cin>>a[i][j];
  11.   }
  12.  }
  13. }
  14. void disp(int d[3][3])
  15. {
  16.  cout<<"\n";
  17.  for(int i=0;i<3;i++)
  18.  {
  19.   for(int j=0;j<3;j++)
  20.   {
  21.    cout<<"\t"<<d[i][j];
  22.   }
  23.   cout<<"\n";
  24.  }
  25. }
  26. int det(int a[3][3])
  27. {
  28. int mod;
  29. mod=(a[0][0]*(a[1][1]*a[2][2]-a[2][1]*a[1][2]))-(a[0][1]*(a[1][0]*a[2][2]-a[2][0]*a[1][2]))+(a[0][2]*(a[1][0]*a[2][1]-a[2][0]*a[1][1]));
  30. cout<<"\nDeterminant of A="<<mod;
  31. return mod;
  32. }
  33. void main()
  34. {
  35. clrscr();
  36. int a[3][3],mod,adj[3][3],co[3][3];
  37. get(a);
  38. disp(a);
  39. mod=det(a);
  40. cout<<"\nA Inverse is (1/Determinant of A)*Adjoint A";
  41.  if(mod==0)
  42.  {
  43.  cout<<"\nInverse doesnt exist.";
  44.  }
  45.  else
  46.  {
  47.  co[0][0]=a[1][1]*a[2][2]-a[2][1]*a[1][2];
  48.  co[0][1]=a[1][2]*a[2][0]-a[2][2]*a[1][0];
  49.  co[0][2]=a[1][0]*a[2][1]-a[2][0]*a[1][1];
  50.  co[1][0]=a[2][1]*a[0][2]-a[0][1]*a[2][2];
  51.  co[1][1]=a[2][2]*a[0][0]-a[0][2]*a[2][0];
  52.  co[1][2]=a[2][0]*a[0][1]-a[0][0]*a[2][1];
  53.  co[2][0]=a[0][1]*a[1][2]-a[1][1]*a[0][2];
  54.  co[2][1]=a[0][2]*a[1][0]-a[1][2]*a[0][0];
  55.  co[2][2]=a[0][0]*a[1][1]-a[1][0]*a[0][1];
  56.  cout<<"\nCofactor matrix...";
  57.  disp(co);
  58.  adj[0][0]=a[1][1]*a[2][2]-a[2][1]*a[1][2];
  59.  adj[1][0]=a[1][2]*a[2][0]-a[2][2]*a[1][0];
  60.  adj[2][0]=a[1][0]*a[2][1]-a[2][0]*a[1][1];
  61.  adj[0][1]=a[2][1]*a[0][2]-a[0][1]*a[2][2];
  62.  adj[1][1]=a[2][2]*a[0][0]-a[0][2]*a[2][0];
  63.  adj[2][1]=a[2][0]*a[0][1]-a[0][0]*a[2][1];
  64.  adj[0][2]=a[0][1]*a[1][2]-a[1][1]*a[0][2];
  65.  adj[1][2]=a[0][2]*a[1][0]-a[1][2]*a[0][0];
  66.  adj[2][2]=a[0][0]*a[1][1]-a[1][0]*a[0][1];
  67.  cout<<"\nAdjoint matrix...";
  68.  disp(adj);
  69.  }
  70. getch();
Now its your turn.Try making a code for 2x2 matrix.If you succeed comment below.


YOU can ask any other program like this in comments or you can  mail me.


No comments:

Post a Comment