Determinant of a matrix

Hi, i want to find the determinant of a matrix. I know how to do it if it is a 3x3 matrix. if i have to take the size of the matrix by the user how am i going to get the determinant. Help would highly be appreciated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;
int main()
{
    int r, c, i, j, k, d=0;
    cout << "Enter number of rows: ";
    cin >> r;
    cout << "Enter number of columns: ";
    cin >> c;
    int a[r][c];
    double det=0;
       
 for(i = 0; i < r; i++){		
       for(j = 0; j < c; j++){
       
           cout << "Enter Number for matrix A: ";
           cin >> a[i][j];
       }
    	}    
		for(i = 0; i < 3; i++)
		det = det + (a[0][i] * (a[1][(i+1)%3] * a[2][(i+2)%3] - a[1][(i+2)%3] * a[2][(i+1)%3]));
		
		cout << "Determinant of the matrix is: "<<det;

    return 0;
}
the 3x3 is a known formula that you can get from any linear algebra book.
or you can compute the eigenvalues and eigenvectors of the matrix and build it from that.
above 5x5 or something the formulas for direct det generation are too complex to fool with (even 3x3 is kinda fat and annoying) and the best way to get it is via the eigens, IMHO.

however, what do you know about your matrix at the point where you need it? If you already solved it, for example, I think you can get the det from the solution.

is this a math question, an algorithm question, or a c++ question?

The det is one of the most useless things in linear algebra, FYI. Once you get bigger than 5x5: If you can get it, you had to do things that told you anything the det could have told you. If you can't get it without a bunch of work, the work to get it is too much compared to just solving the thing you wanted to use the det to get. And if you just want it to print it on the screen, its a pointless exercise for the sake of doing a pointless exercise (you gotta do what the prof wants, though). To put it another way, professors obsess over the det which is pretty cool for 2x2 and 3x3s in a world where practical matrices are often hundreds of columns, eg 500X500, and 10k X10k is not rare.
Last edited on
my question is i know how to create a program where i can find the determinant of a 3x3 matrix. but now i want to create a program when it runs asks the size of the matrix by the user for example of the size of the matrix is 4x4 or 2x2. the user enters the elements of the size of the matrix he chose. and the determinant is calculated. this is a c++ question
ok, for starters, you cannot use variables for array dimensions in pure c++.
That means you need to swap your 2d array for a pointer array or vectors (prefer vectors).

Once you have a valid way to vary the dimensions of your matrix, then you need code.
To do a 10x10, you need to code up a solution ... this is back to a math problem: clearly your 3x3 code won't do it, so you have to decide *how* you want to get the answer (which can be done any of 4 or 5 ways... brute force expansion, eigens, RREF solved, and so on, and I don't remember it all because I don't care to compute the det and its been a long time since school for me). After picking a solution, you will need to code it up, which is going to be several pages of code most likely if you do anything besides the brute force. The brute force is going to be (very) slow for large (modern PC can do a lot here) N, though.

https://math.stackexchange.com/questions/507641/show-that-the-determinant-of-a-is-equal-to-the-product-of-its-eigenvalues

OR
Prove that the determinant of an upper triangular matrix is the product of its diagonal entries.
which means factoring the thing to UT form, which isnt too difficult. Look at the LU decomp:
https://en.wikipedia.org/wiki/LU_decomposition (this is the solved/ RREF approach I mentioned, I had to look up the details)

there are 2 approaches you can look into.

I can't recommend enough building a matrix class so you can have operators like += and * and so on if you are going to go down the rabbit holes. It will quickly reduce many loops and such to simple math expressions that you can follow easily.
Last edited on
You can compute it by the same row operations as you would use for gaussian elimination. Once you have put it in upper-triangular form just take the product of the diagonal elements. (Remember also, that if you do any row swaps for partial pivoting then each swap reverses the sign of the determinant.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;

const double SMALL = 1.0E-30;

using matrix = vector< vector<double> >;

//======================================================================

double determinant( matrix A )
{
   int n = A.size();

   double det = 1;

   // Row operations for i = 0, ,,,, n - 2 (n-1 not needed)
   for ( int i = 0; i < n - 1; i++ )
   {
      // Partial pivot: find row r below with largest element in column i
      int r = i;
      double maxA = abs( A[i][i] );
      for ( int k = i + 1; k < n; k++ )
      {
         double val = abs( A[k][i] );
         if ( val > maxA )
         {
            r = k;
            maxA = val;
         }
      }
      if ( r != i )
      {
         for ( int j = i; j < n; j++ ) swap( A[i][j], A[r][j] );
         det = -det;
      }

      // Row operations to make upper-triangular
      double pivot = A[i][i];
      if ( abs( pivot ) < SMALL ) return 0.0;              // Singular matrix

      for ( int r = i + 1; r < n; r++ )                    // On lower rows
      {
         double multiple = A[r][i] / pivot;                // Multiple of row i to clear element in ith column
         for ( int j = i; j < n; j++ ) A[r][j] -= multiple * A[i][j];
      }
      det *= pivot;                                        // Determinant is product of diagonal
   }

   det *= A[n-1][n-1];

   return det;
}

//======================================================================

int main()
{
   matrix A = { { -2,  2, -3 },             // From Wikipedia; determinant = 18
                { -1,  1,  3 },
                {  2,  0, -1 } };

   matrix B = { {  1,  2,  3,  4,  5,  6 },
                { -2,  5,  5,  7, -1,  0 },
                {  1,  9, 10,  3,  0,  5 },
                { -1, 11, -2,  2,  1,  4 },
                {  0, 19, 10, 13, -1,  4 },
                {  2,  2,  4,  3, -3, -2 } };

   cout << "det( A ) = " << determinant( A ) << '\n';
   cout << "det( B ) = " << determinant( B ) << '\n';
}

//====================================================================== 


det( A ) = 18
det( B ) = 14754
The determinant is fabulously easy to compute, and you don’t need to do anything weird. All you have to do is sum the products of the diagonals, remembering to wrap and handle signs. The 3×3 method you find anywhere online will do, just extend to any M×N dimensional matrix.

[edit] Anyone taking Linear Algebra I knows how to do this by hand.

[edit 2] Fixed language to be more clear:

    ┌ A B C ┐
det │ D E F │ = (AEI + BFG + CDH) - (AFH + BDI + CEG)
    └ G H I ┘
Last edited on
just extend to any M×N dimensional matrix.
What does it mean to find the determinant of a non-square matrix, though?

Also, the formula that Duthomhas is referring to is: https://en.wikipedia.org/wiki/Laplace_expansion
"Cofactor expansion"

Anyone taking Linear Algebra I knows how to do this by hand.
And then they forget about it immediately after and have to re-learn it the next time :(
(Doing anything greater than 3x3 on an exam becomes torture when it's not triangular.)
Last edited on
Non-square matrices do not have inverses, so they do not have determinants... Heh heh heh...

But calculating it is the same, LOL.

Doing anything greater than 3x3 on an exam becomes torture when it's not triangular

Nah, it’s only torture when your professor decides not to use friendly numbers (i.e. small integers or something like that). /muah-hah-hah-hah
You can compute it by the same row operations as you would use for gaussian elimination.

This is the exact same as the LU idea, but more operations, if I recall the complexity of the 2.
I could have that backwards, though.
Topic archived. No new replies allowed.