15,669,039 members
See more:
Well, this is giving me a real headache. I'm building a matrix determinant function to compute NxN determinant, and I'm using recursion. The logic is working right but I'm not able to get the final value computed correctly.

Here is my code for Matrix Determinant:

C#
```public static double determinant(double[,]array){
double det=0;
double total = 0;
double[,] tempArr = new double[array.GetLength(0) - 1, array.GetLength(1) - 1];

if(array.GetLength(0)==2)
{
det = array[0, 0] * array[1, 1] - array[0, 1] * array[1, 0];
}

else {

for (int i = 0; i <1; i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
if (j % 2 != 0) array[i, j] = array[i, j] * -1;
tempArr= fillNewArr(array, i, j);
det+=determinant(tempArr);
total =total + (det * array[i, j]);
}
}
}
return det;
}
```

and about fillNewArr method it's just a method to trim the array, method is as follow:
C#
```public static double[,] fillNewArr(double[,] originalArr, int row, int col)
{
double[,] tempArray = new double[originalArr.GetLength(0) - 1, originalArr.GetLength(1) - 1];

for (int i = 0, newRow = 0; i < originalArr.GetLength(0); i++)
{
if (i == row)
continue;
for (int j = 0, newCol=0; j < originalArr.GetLength(1); j++)
{
if ( j == col) continue;
tempArray[newRow, newCol] = originalArr[i, j];

newCol++;
}
newRow++;
}
return tempArray;

}```

The method is working as it supposed to "I assume" but the final result is not computed in the right way, why would that be?!

4x4 Array Example:

C#
```{2 6 6 2}
{2 7 3 6}
{1 5 0 1}
{3 7 0 7}```

Final result should be -168, while mine is 104!
Posted
Mehdi Gholam 11-Oct-14 2:14am
Obviously your logic is not right if you are not getting the expected answer.

## Solution 1

This is the part where should be modified :)
C#
```for (int j = 0; j < array.GetLength(1); j++)
{
tempArr= fillNewArr(array, 0, j);
det=determinant(tempArr) *( Math.Pow(-1,j)* array[0,j]);
total += det; ;
}```

## Solution 2

Saruss' Rule can be useful for faster & memory efficient computation of Determinant. because it is non recursive. You can get application on https://github.com/apanasara/Faster_nxn_Determinant

OriginalGriff 15-Dec-19 1:49am
While I applaud your urge to help people, it's a good idea to stick to new questions, rather than 5 year old ones. After that amount of time, it's unlikely that the original poster is at all interested in the problem any more!
Answering old questions can be seen as rep-point hunting, which is a form of site abuse. The more trigger happy amongst us will start the process of banning you from the site if you aren't careful. Stick to new questions and you'll be fine.

Top Experts
Last 24hrsThis month
 OriginalGriff 83 Graeme_Grant 75 Dave Kreskowiak 58 Richard MacCutchan 40 Le lance Flamer 24
 OriginalGriff 1,040 Richard MacCutchan 202 Patrice T 110 Graeme_Grant 100 Richard Deeming 50

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900