HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Calculating n x n determinant

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
determinantcalculatingstackoverflow

Problem

According to instructions and sample code from MSDN Magazine and comments from post here determinant of n x n...

I changed code to be like this:

```
using System;

internal class MatrixDecompositionProgram
{
private static void Main(string[] args)
{
float[,] m = MatrixCreate(4, 4);
m[0, 0] = 3.0f; m[0, 1] = 7.0f; m[0, 2] = 2.0f; m[0, 3] = 5.0f;
m[1, 0] = 1.0f; m[1, 1] = 8.0f; m[1, 2] = 4.0f; m[1, 3] = 2.0f;
m[2, 0] = 2.0f; m[2, 1] = 1.0f; m[2, 2] = 9.0f; m[2, 3] = 3.0f;
m[3, 0] = 5.0f; m[3, 1] = 4.0f; m[3, 2] = 7.0f; m[3, 3] = 1.0f;

int[] perm;
int toggle;

float[,] luMatrix = MatrixDecompose(m, out perm, out toggle);

float[,] lower = ExtractLower(luMatrix);
float[,] upper = ExtractUpper(luMatrix);

float det = MatrixDeterminant(m);

Console.WriteLine("Determinant of m computed via decomposition = " + det.ToString("F1"));
}

// --------------------------------------------------------------------------------------------------------------
private static float[,] MatrixCreate(int rows, int cols)
{
// allocates/creates a matrix initialized to all 0.0. assume rows and cols > 0
// do error checking here
float[,] result = new float[rows, cols];
return result;
}

// --------------------------------------------------------------------------------------------------------------
private static float[,] MatrixDecompose(float[,] matrix, out int[] perm, out int toggle)
{
// Doolittle LUP decomposition with partial pivoting.
// rerturns: result is L (with 1s on diagonal) and U; perm holds row permutations; toggle is +1 or -1 (even or odd)
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);

//Check if matrix is square
if (rows != cols)
throw new Exception("Attempt to MatrixDecompose a non-square mattrix");

float[,] result = MatrixDup

Solution

Optimizing for performance and readability you may want to avoid the 3 executions of the same loop:

for (int k = 0; k < result.GetLength(1); k++){
    var swapTemp = result[pRow, k];
    result[pRow, k] = result[j, k]
    result[j, k] = swapTemp;
}


You may also want to loop backwards (try it and see if it works out better for you):

for (int k = result.GetLength(1)-1; k >= 0; k--)


And finally, something a little non-intuitive. Use double over float for accuracy and speed in .NET as your floats are probably converted to double anyway. CLR via C# covers this quirk but again, test it out as things may have changed.

Code Snippets

for (int k = 0; k < result.GetLength(1); k++){
    var swapTemp = result[pRow, k];
    result[pRow, k] = result[j, k]
    result[j, k] = swapTemp;
}
for (int k = result.GetLength(1)-1; k >= 0; k--)

Context

StackExchange Code Review Q#24336, answer score: 2

Revisions (0)

No revisions yet.