1. ## Determinant calculation

Does someone have any C++ code that calculates the determinant of an arbitary nxn matrix?

I assure you, that this is in no way a homework assignment.
I also assure you that I belive myself capable of writing my own algorithm, if some time is invested.

I just hate reinventing the wheel, that's all. A fast google search didn't return any relevant results, neither did a search on these boards.

2. Here's a quick scratchy one. I assumed you were using dynamic arrays instead of std::vectors:
Code:
```#include <iostream>
#include <algorithm>

const int N = 3;

double matrix_det ( double **in_matrix, int n )
{
int i, j, k;
double **matrix;
double det = 1;

matrix = new double *[n];

for ( i = 0; i < n; i++ )
matrix[i] = new double[n];

for ( i = 0; i < n; i++ ) {
for ( j = 0; j < n; j++ )
matrix[i][j] = in_matrix[i][j];
}

for ( k = 0; k < n; k++ ) {
if ( matrix[k][k] == 0 ) {
bool ok = false;

for ( j = k; j < n; j++ ) {
if ( matrix[j][k] != 0 )
ok = true;
}

if ( !ok )
return 0;

for ( i = k; i < n; i++ )
std::swap ( matrix[i][j], matrix[i][k] );

det = -det;
}

det *= matrix[k][k];

if ( k + 1 < n ) {
for ( i = k + 1; i < n; i++ ) {
for ( j = k + 1; j < n; j++ )
matrix[i][j] = matrix[i][j] - matrix[i][k] *
matrix[k][j] / matrix[k][k];
}
}
}

for ( i = 0; i < n; i++ )
delete [] matrix[i];

delete [] matrix;

return det;
}

int main()
{
int i;
double **array;

array = new double *[N];

for ( i = 0; i < N; i++ )
array[i] = new double[N];

array[0][0] = 4.0;
array[0][1] = 6.0;
array[0][2] = 3.0;

array[1][0] = 9.0;
array[1][1] = 1.0;
array[1][2] = 6.0;

array[2][0] = 5.0;
array[2][1] = 9.0;
array[2][2] = 2.0;

std::cout<< matrix_det ( array, N ) <<std::endl;

for ( i = 0; i < N; i++ )
delete [] array[i];

delete [] array;
}```
-Prelude

3. Thanks alot!
That was exactly what I was looking for!

I think I'll add some optimizations for the simple cases n=2 and n=3.

4. Although definitely not as efficient as Prelude's code, I still like my determinant function. It calculates it via expansion by minors/cofactors with recursion.

Code:
```Matrix findMinor(Matrix *A, int row, int col)
{
int x;
int y;
int a;
a = A->numR();
int b;
b = A->numC();
Matrix M(a-1,b-1);

for(x=0; x<a; x++)
{
for(y=0; y<b; y++)
{
if(x == (row-1));
if(y == (col-1));

if(x > (row-1) && y > (col-1)) M.Array[x-1][y-1] = A->Array[x][y];
if(x > (row-1)) M.Array[x-1][y] = A->Array[x][y];
if(y > (col-1)) M.Array[x][y-1] = A->Array[x][y];
else M.Array[x][y] = A->Array[x][y];
}
}

return M;
}

float Matrix::Determinant()
{
float det;
Matrix temp;
float temp2;
float multiple;
int y;
det = 0;
if(a==b && b==2)
{
det = (Array[0][0]*Array[1][1])-(Array[0][1]*Array[1][0]);
return det;
}
if(a != b)
{
return 0;
}
else
{
for(y=0; y<b; y++)
{
if(y == b) break;
else
{
multiple = power(-1, y);
temp = findMinor(this,1,y+1);
temp2 = temp.Determinant();
det = (multiple * (Array[0][y] * temp2)) + det;
}
}
return det;
}
}```