Skip to content

Instantly share code, notes, and snippets.

@dilijev
Created December 20, 2012 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dilijev/4349065 to your computer and use it in GitHub Desktop.
Save dilijev/4349065 to your computer and use it in GitHub Desktop.
/**
Compile with
g++ matrix.cpp -o matrix
Run with
./matrix
*/
#include <vector>
#include <iostream>
#include <cmath>
#include <malloc.h>
using namespace std;
#define SIZE 3
double Determinant(double**,int);
int main() {
double a[SIZE][SIZE] = { {1,1,3}, {3,2,3}, {3,3,2} };
double** minerals = new double*[SIZE];
for (int i=0; i<SIZE; i++) {
minerals[i] = new double[SIZE];
for (int j=0; j<SIZE; j++) {
minerals[i][j] = a[i][j];
}
}
// TODO your code
double result = Determinant(minerals, SIZE);
cout << result << endl; // result should be 7
// remember to free your allocated memory
for (int i=0; i<SIZE; i++) {
delete [] minerals[i];
}
delete [] minerals;
}
/*
Recursive definition of determinate using expansion by minors.
*/
double Determinant(double **a,int n)
{
int i,j,j1,j2;
double det = 0;
double **m = NULL;
if (n < 1) { /* Error */
} else if (n == 1) { /* Shouldn't get used */
det = a[0][0];
} else if (n == 2) {
det = a[0][0] * a[1][1] - a[1][0] * a[0][1];
} else {
det = 0;
for (j1=0;j1<n;j1++) {
m = (double**)malloc((n-1)*sizeof(double *));
for (i=0;i<n-1;i++)
m[i] = (double*)malloc((n-1)*sizeof(double));
for (i=1;i<n;i++) {
j2 = 0;
for (j=0;j<n;j++) {
if (j == j1)
continue;
m[i-1][j2] = a[i][j];
j2++;
}
}
det += pow(-1.0,j1+2.0) * a[0][j1] * Determinant(m,n-1);
for (i=0;i<n-1;i++)
free(m[i]);
free(m);
}
}
return(det);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment