C++ Program to Find Inverse of a Matrix

This is a C++ Program to find the inverse of matrix. The inverse of any matrix exists only if its determinant is not zero.

Here is source code of the C++ Program to Find Inverse of a Matrix. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #if !defined(MATRIX_H)
  2. #define MATRIX_H
  3. #include <stdio.h>
  4. #include <iostream>
  5. #include <tchar.h>
  6. #include <math.h>
  7. #include <stdlib.h>
  8. class CMatrix
  9. {
  10.     private:
  11.         int m_rows;
  12.         int m_cols;
  13.         char m_name[128];
  14.         CMatrix();
  15.     public:
  16.         double **m_pData;
  17.         CMatrix(const char *name, int rows, int cols) :
  18.             m_rows(rows), m_cols(cols)
  19.         {
  20.             strcpy(m_name, name);
  21.             m_pData = new double*[m_rows];
  22.             for (int i = 0; i < m_rows; i++)
  23.                 m_pData[i] = new double[m_cols];
  24.             for (int i = 0; i < m_rows; i++)
  25.             {
  26.                 for (int j = 0; j < m_cols; j++)
  27.                 {
  28.                     m_pData[i][j] = 0.0;
  29.                 }
  30.             }
  31.         }
  32.         CMatrix(const CMatrix &other)
  33.         {
  34.             strcpy(m_name, other.m_name);
  35.             m_rows = other.m_rows;
  36.             m_cols = other.m_cols;
  37.             m_pData = new double*[m_rows];
  38.             for (int i = 0; i < m_rows; i++)
  39.                 m_pData[i] = new double[m_cols];
  40.             for (int i = 0; i < m_rows; i++)
  41.             {
  42.                 for (int j = 0; j < m_cols; j++)
  43.                 {
  44.                     m_pData[i][j] = other.m_pData[i][j];
  45.                 }
  46.             }
  47.         }
  48.         ~CMatrix()
  49.         {
  50.             for (int i = 0; i < m_rows; i++)
  51.                 delete[] m_pData[i];
  52.             delete[] m_pData;
  53.             m_rows = m_cols = 0;
  54.         }
  55.         void SetName(const char *name)
  56.         {
  57.             strcpy(m_name, name);
  58.         }
  59.         const char* GetName() const
  60.         {
  61.             return m_name;
  62.         }
  63.         void GetInput()
  64.         {
  65.             std::cin >> *this;
  66.         }
  67.         void FillSimulatedInput()
  68.         {
  69.             static int factor1 = 1, factor2 = 2;
  70.             std::cout << "\n\nEnter Input For Matrix : " << m_name << " Rows: "
  71.                     << m_rows << " Cols: " << m_cols << "\n";
  72.             for (int i = 0; i < m_rows; i++)
  73.             {
  74.                 for (int j = 0; j < m_cols; j++)
  75.                 {
  76.                     std::cout << "Input For Row: " << i + 1 << " Col: " << j
  77.                             + 1 << " = ";
  78.                     int data = ((i + 1) * factor1) + (j + 1) * factor2;
  79.                     m_pData[i][j] = data / 10.2;
  80.                     std::cout << m_pData[i][j] << "\n";
  81.                     factor1 += (rand() % 4);
  82.                     factor2 += (rand() % 3);
  83.                 }
  84.                 std::cout << "\n";
  85.             }
  86.             std::cout << "\n";
  87.         }
  88.         double Determinant()
  89.         {
  90.             double det = 0;
  91.             double **pd = m_pData;
  92.             switch (m_rows)
  93.             {
  94.                 case 2:
  95.                 {
  96.                     det = pd[0][0] * pd[1][1] - pd[0][1] * pd[1][0];
  97.                     return det;
  98.                 }
  99.                     break;
  100.                 case 3:
  101.                 {
  102.                     /***
  103.                      a b c
  104.                      d e f
  105.                      g h i
  106.  
  107.                      a b c a b c
  108.                      d e f d e f
  109.                      g h i g h i
  110.  
  111.                      // det (A) = aei + bfg + cdh - afh - bdi - ceg.
  112.                      ***/
  113.                     double a = pd[0][0];
  114.                     double b = pd[0][1];
  115.                     double c = pd[0][2];
  116.                     double d = pd[1][0];
  117.                     double e = pd[1][1];
  118.                     double f = pd[1][2];
  119.                     double g = pd[2][0];
  120.                     double h = pd[2][1];
  121.                     double i = pd[2][2];
  122.                     double det = (a * e * i + b * f * g + c * d * h);
  123.                     det = det - a * f * h;
  124.                     det = det - b * d * i;
  125.                     det = det - c * e * g;
  126.                     return det;
  127.                 }
  128.                     break;
  129.                 case 4:
  130.                 {
  131.                     CMatrix *temp[4];
  132.                     for (int i = 0; i < 4; i++)
  133.                         temp[i] = new CMatrix("", 3, 3);
  134.                     for (int k = 0; k < 4; k++)
  135.                     {
  136.                         for (int i = 1; i < 4; i++)
  137.                         {
  138.                             int j1 = 0;
  139.                             for (int j = 0; j < 4; j++)
  140.                             {
  141.                                 if (k == j)
  142.                                     continue;
  143.                                 temp[k]->m_pData[i - 1][j1++]
  144.                                         = this->m_pData[i][j];
  145.                             }
  146.                         }
  147.                     }
  148.                     double det = this->m_pData[0][0] * temp[0]->Determinant()
  149.                             - this->m_pData[0][1] * temp[1]->Determinant()
  150.                             + this->m_pData[0][2] * temp[2]->Determinant()
  151.                             - this->m_pData[0][3] * temp[3]->Determinant();
  152.                     return det;
  153.                 }
  154.                     break;
  155.                 case 5:
  156.                 {
  157.                     CMatrix *temp[5];
  158.                     for (int i = 0; i < 5; i++)
  159.                         temp[i] = new CMatrix("", 4, 4);
  160.                     for (int k = 0; k < 5; k++)
  161.                     {
  162.                         for (int i = 1; i < 5; i++)
  163.                         {
  164.                             int j1 = 0;
  165.                             for (int j = 0; j < 5; j++)
  166.                             {
  167.                                 if (k == j)
  168.                                     continue;
  169.                                 temp[k]->m_pData[i - 1][j1++]
  170.                                         = this->m_pData[i][j];
  171.                             }
  172.                         }
  173.                     }
  174.                     double det = this->m_pData[0][0] * temp[0]->Determinant()
  175.                             - this->m_pData[0][1] * temp[1]->Determinant()
  176.                             + this->m_pData[0][2] * temp[2]->Determinant()
  177.                             - this->m_pData[0][3] * temp[3]->Determinant()
  178.                             + this->m_pData[0][4] * temp[4]->Determinant();
  179.                     return det;
  180.                 }
  181.                 case 6:
  182.                 case 7:
  183.                 case 8:
  184.                 case 9:
  185.                 case 10:
  186.                 case 11:
  187.                 case 12:
  188.                 default:
  189.                 {
  190.                     int DIM = m_rows;
  191.                     CMatrix **temp = new CMatrix*[DIM];
  192.                     for (int i = 0; i < DIM; i++)
  193.                         temp[i] = new CMatrix("", DIM - 1, DIM - 1);
  194.                     for (int k = 0; k < DIM; k++)
  195.                     {
  196.                         for (int i = 1; i < DIM; i++)
  197.                         {
  198.                             int j1 = 0;
  199.                             for (int j = 0; j < DIM; j++)
  200.                             {
  201.                                 if (k == j)
  202.                                     continue;
  203.                                 temp[k]->m_pData[i - 1][j1++]
  204.                                         = this->m_pData[i][j];
  205.                             }
  206.                         }
  207.                     }
  208.                     double det = 0;
  209.                     for (int k = 0; k < DIM; k++)
  210.                     {
  211.                         if ((k % 2) == 0)
  212.                             det = det + (this->m_pData[0][k]
  213.                                     * temp[k]->Determinant());
  214.                         else
  215.                             det = det - (this->m_pData[0][k]
  216.                                     * temp[k]->Determinant());
  217.                     }
  218.                     for (int i = 0; i < DIM; i++)
  219.                         delete temp[i];
  220.                     delete[] temp;
  221.                     return det;
  222.                 }
  223.                     break;
  224.             }
  225.         }
  226.         CMatrix& operator =(const CMatrix &other)
  227.         {
  228.             if (this->m_rows != other.m_rows || this->m_cols != other.m_cols)
  229.             {
  230.                 std::cout
  231.                         << "WARNING: Assignment is taking place with by changing the number of rows and columns of the matrix";
  232.             }
  233.             for (int i = 0; i < m_rows; i++)
  234.                 delete[] m_pData[i];
  235.             delete[] m_pData;
  236.             m_rows = m_cols = 0;
  237.             strcpy(m_name, other.m_name);
  238.             m_rows = other.m_rows;
  239.             m_cols = other.m_cols;
  240.             m_pData = new double*[m_rows];
  241.             for (int i = 0; i < m_rows; i++)
  242.                 m_pData[i] = new double[m_cols];
  243.             for (int i = 0; i < m_rows; i++)
  244.             {
  245.                 for (int j = 0; j < m_cols; j++)
  246.                 {
  247.                     m_pData[i][j] = other.m_pData[i][j];
  248.                 }
  249.             }
  250.             return *this;
  251.         }
  252.         CMatrix CoFactor()
  253.         {
  254.             CMatrix cofactor("COF", m_rows, m_cols);
  255.             if (m_rows != m_cols)
  256.                 return cofactor;
  257.             if (m_rows < 2)
  258.                 return cofactor;
  259.             else if (m_rows == 2)
  260.             {
  261.                 cofactor.m_pData[0][0] = m_pData[1][1];
  262.                 cofactor.m_pData[0][1] = -m_pData[1][0];
  263.                 cofactor.m_pData[1][0] = -m_pData[0][1];
  264.                 cofactor.m_pData[1][1] = m_pData[0][0];
  265.                 return cofactor;
  266.             }
  267.             else if (m_rows >= 3)
  268.             {
  269.                 int DIM = m_rows;
  270.                 CMatrix ***temp = new CMatrix**[DIM];
  271.                 for (int i = 0; i < DIM; i++)
  272.                     temp[i] = new CMatrix*[DIM];
  273.                 for (int i = 0; i < DIM; i++)
  274.                     for (int j = 0; j < DIM; j++)
  275.                         temp[i][j] = new CMatrix("", DIM - 1, DIM - 1);
  276.                 for (int k1 = 0; k1 < DIM; k1++)
  277.                 {
  278.                     for (int k2 = 0; k2 < DIM; k2++)
  279.                     {
  280.                         int i1 = 0;
  281.                         for (int i = 0; i < DIM; i++)
  282.                         {
  283.                             int j1 = 0;
  284.                             for (int j = 0; j < DIM; j++)
  285.                             {
  286.                                 if (k1 == i || k2 == j)
  287.                                     continue;
  288.                                 temp[k1][k2]->m_pData[i1][j1++]
  289.                                         = this->m_pData[i][j];
  290.                             }
  291.                             if (k1 != i)
  292.                                 i1++;
  293.                         }
  294.                     }
  295.                 }
  296.                 bool flagPositive = true;
  297.                 for (int k1 = 0; k1 < DIM; k1++)
  298.                 {
  299.                     flagPositive = ((k1 % 2) == 0);
  300.                     for (int k2 = 0; k2 < DIM; k2++)
  301.                     {
  302.                         if (flagPositive == true)
  303.                         {
  304.                             cofactor.m_pData[k1][k2]
  305.                                     = temp[k1][k2]->Determinant();
  306.                             flagPositive = false;
  307.                         }
  308.                         else
  309.                         {
  310.                             cofactor.m_pData[k1][k2]
  311.                                     = -temp[k1][k2]->Determinant();
  312.                             flagPositive = true;
  313.                         }
  314.                     }
  315.                 }
  316.                 for (int i = 0; i < DIM; i++)
  317.                     for (int j = 0; j < DIM; j++)
  318.                         delete temp[i][j];
  319.                 for (int i = 0; i < DIM; i++)
  320.                     delete[] temp[i];
  321.                 delete[] temp;
  322.             }
  323.             return cofactor;
  324.         }
  325.         CMatrix Adjoint()
  326.         {
  327.             CMatrix cofactor("COF", m_rows, m_cols);
  328.             CMatrix adj("ADJ", m_rows, m_cols);
  329.             if (m_rows != m_cols)
  330.                 return adj;
  331.             cofactor = this->CoFactor();
  332.             // adjoint is transpose of a cofactor of a matrix
  333.             for (int i = 0; i < m_rows; i++)
  334.             {
  335.                 for (int j = 0; j < m_cols; j++)
  336.                 {
  337.                     adj.m_pData[j][i] = cofactor.m_pData[i][j];
  338.                 }
  339.             }
  340.             return adj;
  341.         }
  342.         CMatrix Transpose()
  343.         {
  344.             CMatrix trans("TR", m_cols, m_rows);
  345.             for (int i = 0; i < m_rows; i++)
  346.             {
  347.                 for (int j = 0; j < m_cols; j++)
  348.                 {
  349.                     trans.m_pData[j][i] = m_pData[i][j];
  350.                 }
  351.             }
  352.             return trans;
  353.         }
  354.         CMatrix Inverse()
  355.         {
  356.             CMatrix cofactor("COF", m_rows, m_cols);
  357.             CMatrix inv("INV", m_rows, m_cols);
  358.             if (m_rows != m_cols)
  359.                 return inv;
  360.             // to find out Determinant
  361.             double det = Determinant();
  362.             cofactor = this->CoFactor();
  363.             // inv = transpose of cofactor / Determinant
  364.             for (int i = 0; i < m_rows; i++)
  365.             {
  366.                 for (int j = 0; j < m_cols; j++)
  367.                 {
  368.                     inv.m_pData[j][i] = cofactor.m_pData[i][j] / det;
  369.                 }
  370.             }
  371.             return inv;
  372.         }
  373.         CMatrix operator +(const CMatrix &other)
  374.         {
  375.             if (this->m_rows != other.m_rows || this->m_cols != other.m_cols)
  376.             {
  377.                 std::cout
  378.                         << "Addition could not take place because number of rows and columns are different between the two matrices";
  379.                 return *this;
  380.             }
  381.             CMatrix result("", m_rows, m_cols);
  382.             for (int i = 0; i < m_rows; i++)
  383.             {
  384.                 for (int j = 0; j < m_cols; j++)
  385.                 {
  386.                     result.m_pData[i][j] = this->m_pData[i][j]
  387.                             + other.m_pData[i][j];
  388.                 }
  389.             }
  390.             return result;
  391.         }
  392.         CMatrix operator -(const CMatrix &other)
  393.         {
  394.             if (this->m_rows != other.m_rows || this->m_cols != other.m_cols)
  395.             {
  396.                 std::cout
  397.                         << "Subtraction could not take place because number of rows and columns are different between the two matrices";
  398.                 return *this;
  399.             }
  400.             CMatrix result("", m_rows, m_cols);
  401.             for (int i = 0; i < m_rows; i++)
  402.             {
  403.                 for (int j = 0; j < m_cols; j++)
  404.                 {
  405.                     result.m_pData[i][j] = this->m_pData[i][j]
  406.                             - other.m_pData[i][j];
  407.                 }
  408.             }
  409.             return result;
  410.         }
  411.         CMatrix operator *(const CMatrix &other)
  412.         {
  413.             if (this->m_cols != other.m_rows)
  414.             {
  415.                 std::cout
  416.                         << "Multiplication could not take place because number of columns of 1st Matrix and number of rows in 2nd Matrix are different";
  417.                 return *this;
  418.             }
  419.             CMatrix result("", this->m_rows, other.m_cols);
  420.             for (int i = 0; i < this->m_rows; i++)
  421.             {
  422.                 for (int j = 0; j < other.m_cols; j++)
  423.                 {
  424.                     for (int k = 0; k < this->m_cols; k++)
  425.                     {
  426.                         result.m_pData[i][j] += this->m_pData[i][k]
  427.                                 * other.m_pData[k][j];
  428.                     }
  429.                 }
  430.             }
  431.             return result;
  432.         }
  433.         bool operator ==(const CMatrix &other)
  434.         {
  435.             if (this->m_rows != other.m_rows || this->m_cols != other.m_cols)
  436.             {
  437.                 std::cout
  438.                         << "Comparision could not take place because number of rows and columns are different between the two matrices";
  439.                 return false;
  440.             }
  441.             CMatrix result("", m_rows, m_cols);
  442.             bool bEqual = true;
  443.             for (int i = 0; i < m_rows; i++)
  444.             {
  445.                 for (int j = 0; j < m_cols; j++)
  446.                 {
  447.                     if (this->m_pData[i][j] != other.m_pData[i][j])
  448.                         bEqual = false;
  449.                 }
  450.             }
  451.             return bEqual;
  452.         }
  453.         friend std::istream& operator >>(std::istream &is, CMatrix &m);
  454.         friend std::ostream& operator <<(std::ostream &os, const CMatrix &m);
  455. };
  456. std::istream& operator >>(std::istream &is, CMatrix &m)
  457. {
  458.     std::cout << "\n\nEnter Input For Matrix : " << m.m_name << " Rows: "
  459.             << m.m_rows << " Cols: " << m.m_cols << "\n";
  460.     for (int i = 0; i < m.m_rows; i++)
  461.     {
  462.         for (int j = 0; j < m.m_cols; j++)
  463.         {
  464.             std::cout << "Input For Row: " << i + 1 << " Col: " << j + 1
  465.                     << " = ";
  466.             is >> m.m_pData[i][j];
  467.         }
  468.         std::cout << "\n";
  469.     }
  470.     std::cout << "\n";
  471.     return is;
  472. }
  473. std::ostream& operator <<(std::ostream &os, const CMatrix &m)
  474. {
  475.  
  476.     os << "\n\nMatrix : " << m.m_name << " Rows: " << m.m_rows << " Cols: "
  477.             << m.m_cols << "\n\n";
  478.     for (int i = 0; i < m.m_rows; i++)
  479.     {
  480.         os << " | ";
  481.         for (int j = 0; j < m.m_cols; j++)
  482.         {
  483.             char buf[32];
  484.             double data = m.m_pData[i][j];
  485.             if (m.m_pData[i][j] > -0.00001 && m.m_pData[i][j] < 0.00001)
  486.                 data = 0;
  487.             sprintf(buf, "%10.2lf ", data);
  488.             os << buf;
  489.         }
  490.         os << "|\n";
  491.     }
  492.     os << "\n\n";
  493.     return os;
  494. }
  495. #endif
  496. int main()
  497. {
  498.     CMatrix a("A", 5, 5);
  499.     //std::cin >> a;
  500.     a.FillSimulatedInput();
  501.     CMatrix aadj = a.Inverse();
  502.     std::cout << a;
  503.     std::cout << aadj;
  504.     CMatrix unit = (a * aadj);
  505.     unit.SetName("A * A-Inv");
  506.     std::cout << unit;
  507. }

Output:

$ g++ InverseOfMatrix.cpp
$ a.out
 
Enter Input For Matrix : 
A Rows: 5 
Cols: 5
Input For Row: 1 Col: 1 = 0.294118
Input For Row: 1 Col: 2 = 0.980392
Input For Row: 1 Col: 3 = 1.86275
Input For Row: 1 Col: 4 = 2.84314
Input For Row: 1 Col: 5 = 3.62745
 
Input For Row: 2 Col: 1 = 2.54902
Input For Row: 2 Col: 2 = 3.92157
Input For Row: 2 Col: 3 = 5.09804
Input For Row: 2 Col: 4 = 7.05882
Input For Row: 2 Col: 5 = 9.80392
 
Input For Row: 3 Col: 1 = 6.66667
Input For Row: 3 Col: 2 = 8.92157
Input For Row: 3 Col: 3 = 10.8824
Input For Row: 3 Col: 4 = 12.6471
Input For Row: 3 Col: 5 = 15.3922
 
Input For Row: 4 Col: 1 = 12.0588
Input For Row: 4 Col: 2 = 15.098
Input For Row: 4 Col: 3 = 18.1373
Input For Row: 4 Col: 4 = 20.7843
Input For Row: 4 Col: 5 = 24.4118
 
Input For Row: 5 Col: 1 = 21.1765
Input For Row: 5 Col: 2 = 24.7059
Input For Row: 5 Col: 3 = 27.7451
Input For Row: 5 Col: 4 = 31.0784
Input For Row: 5 Col: 5 = 34.3137
 
Matrix : A Rows: 5 Cols: 5
 
 |       0.29       0.98       1.86       2.84       3.63 |
 |       2.55       3.92       5.10       7.06       9.80 |
 |       6.67       8.92      10.88      12.65      15.39 |
 |      12.06      15.10      18.14      20.78      24.41 |
 |      21.18      24.71      27.75      31.08      34.31 |
 
Matrix : INV Rows: 5 Cols: 5
 
 |      -0.93       0.80      -3.74       2.86      -0.49 |
 |       0.37      -0.32       5.35      -4.91       1.14 |
 |      -0.78      -0.93      -1.46       2.96      -1.10 |
 |       2.37      -0.10       0.25      -1.65       0.84 |
 |      -1.21       0.57      -0.58       0.87      -0.36 |
 
Matrix : A * A-Inv Rows: 5 Cols: 5
 
 |       1.00       0.00       0.00       0.00       0.00 |
 |       0.00       1.00       0.00       0.00       0.00 |
 |       0.00       0.00       1.00       0.00       0.00 |
 |       0.00       0.00       0.00       1.00       0.00 |
 |       0.00       0.00       0.00       0.00       1.00 |

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement

Here’s the list of Best Books in C++ Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.