Created
December 20, 2012 22:19
-
-
Save dilijev/4349065 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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