I'm working on a program where I have to write a method that will find the determinant of a matrix and I'm having some trouble. This is what I have so far.
public Matrix determinant() {
Matrix determinantM = new Matrix(this.rows, this.columns);
for(int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
determinantM.data[r][c] = this.data[r][c];
}
}
Matrix x = (determinantM.data[1][1] * determinantM.data[2][2]) - (determinantM.data[2][1] * determinantM.data[1][2]);
Matrix y = (determinantM.data[1][0] * determinantM.data[2][2]) - (determinantM.data[2][0] * determinantM.data[1][2]);
Matrix z = (determinantM.data[1][0] * determinantM.data[2][1]) - (determinantM.data[2][0] * determinantM.data[1][1]);
Matrix newD = (determinantM.data[0][0] * x) - (determinantM.data[0][1] * y) + (determinantM.data[0][2] * 2);
return newD;
}
and this is how I'm trying to call it from main
Matrix z = new Matrix(new double[][]{{1, 2, 3},{0, 4, 5},{1, 0, 6}});
Matrix v = z.determinant();
System.out.println("v:\n" + v);
I'm not really sure if this is the right way to approach this problem or if I just have some mistakes within my code. I would really appreciate any help.
As stated here to calculate the determinant of a 3x3 matrix like:
The determinant will be:
Therefore, this part of your code:
should actually be:
Then the determinate would be
x - y + z
;So you final method should be something like:
Since you are not modifying the original matrix, you do not need to make a copy out of it.
This code naturally, only works for matrix
3x3
.