How do you calculate the determinant of an NxN matrix C# ?
Reduce to upper triangular form, then make a nested loop where you multiply all the values at position i == j together. There you have it.
5 minutes ago ?...nope not a clue...didn't even know a matrix could have a determinant. Didn't even know the word determinant existed.
Now ?..Absolutely...just wrote some test code...works like a charm.
My method ?...Sure babe....Here ya go..served up on a silver platter.
[1] Google search for say: c# matrix determinant
[2] Pick say ~10 sites that are not obvious chaff.
[3] Have a quick look at the source code on the site...pick some code that is well structured and has plenty of comments.
[4] Pop it into visual studio..write some quciky code that excises the algorithm.
[5] Check a few of the results by hand. If they fail goto step 3.
[6] Run through the code until you understand how it works.
And there you go..How to calculate an n x n matrix determinant in 6 pain free steps.
Determinants Galore.
Can I get you another cocktail ?
The OP posted another question asking specifically about 4x4 matrices, which has been closed as an exact duplicate of this question. Well, if you're not looking for a general solution but instead are constrained to 4x4 matrices alone, then you can use this ugly looking but tried-and-true code:
public double GetDeterminant() {
var m = _values;
return
m[12] * m[9] * m[6] * m[3] - m[8] * m[13] * m[6] * m[3] -
m[12] * m[5] * m[10] * m[3] + m[4] * m[13] * m[10] * m[3] +
m[8] * m[5] * m[14] * m[3] - m[4] * m[9] * m[14] * m[3] -
m[12] * m[9] * m[2] * m[7] + m[8] * m[13] * m[2] * m[7] +
m[12] * m[1] * m[10] * m[7] - m[0] * m[13] * m[10] * m[7] -
m[8] * m[1] * m[14] * m[7] + m[0] * m[9] * m[14] * m[7] +
m[12] * m[5] * m[2] * m[11] - m[4] * m[13] * m[2] * m[11] -
m[12] * m[1] * m[6] * m[11] + m[0] * m[13] * m[6] * m[11] +
m[4] * m[1] * m[14] * m[11] - m[0] * m[5] * m[14] * m[11] -
m[8] * m[5] * m[2] * m[15] + m[4] * m[9] * m[2] * m[15] +
m[8] * m[1] * m[6] * m[15] - m[0] * m[9] * m[6] * m[15] -
m[4] * m[1] * m[10] * m[15] + m[0] * m[5] * m[10] * m[15];
}
It assumes you store your vector data in a 16-element array called _values
(of double
in this case, but float
would work too), in the following order:
0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
12, 13, 14, 15
The standard method is LU decomposition. You may want to use a library instead of coding it yourself. I don't know about C#, but the 40-year standard is LAPACK.