Hello
I am trying to write a matrix calculator but I have some problems.I use cofactor method for calculation.If you don't know the this method you can learn it here easily: http://paulbourke.net/miscellaneous/determinant/
I use two function 1- GetMinor() 2- matrixCofactor() that the first one give me the minor matrix and I calculate determinant recursively in matrixCofactor() and print the determinant of the every matrix and its sub matrixes in every step. I don't know where the problem reside but I predict maybe problem be from recursive calls.I attach all my code file but I think this two function is enough for getting what is happening:

int GetMinor(Matrix *src,Matrix *dest, int row, int col, int order)
	{
	    // indicate which col and row is being copied to dest

	    int colCount = 0,rowCount = 0;
	    int i,j;

	    for(i = 0; i < order; i++ ){
	        if( i != row )
	        {
	            colCount = 0;
	            for( j = 0; j < order; j++ )
	            {
	                // when j is not the element
	                if( j != col )
	                {
	                    dest->elements[rowCount][colCount] = src->elements[i][j];
	                    colCount++;
	                }
	            }
	            rowCount++;
	        }
	    }
	    return 0;
	}

	int matrixCofact(Matrix* mat,int order,double* determinan){
		int i;
		Matrix* minor;
		minor = malloc(sizeof(double));
		newMatrix(order-1,order-1,minor);
		double* det;
		det = malloc(sizeof(double));
		if( order == 1 ){
			printf("The End");
		}
		for(i = 0; i <order;i++){
			GetMinor( mat, minor, 0, i, order);
			printf("\n");
			matrixPrint(minor);
			if( minor->colCount > 3){
				*det += pow(-1.0,i+0) * minor->elements[1][i] * matrixCofact(minor,order-1,det);
				printf("\nThe matrix determinant is: %f",*det);
			}else{
				matrix3dDeterminan(minor,det);
				printf("\nThe matrix determinant is: %f",*det);
			}
		}
		printf("BYE ");
		return 0;
	}

Dani AI

Generated

This thread shows the usual pitfalls of a Laplace (cofactor) implementation. The three most important fixes are: keep the recursive API simple, fix allocations/initialization, and use explicit base cases. was correct to recommend returning a double rather than juggling a pointer accumulator; 's advice to add assertions for index ranges will quickly expose out‑of‑bounds accesses; and 's later note about the base‑case check points at the same class of bug (incorrect termination condition).

Concrete, safe steps to apply:

  • Change the recursive function to return a double and use a local double det = 0.0; accumulator (remove the third pointer parameter). That avoids using an uninitialized *det.
  • When expanding along the first row, multiply by the original element mat->elements[0][i] (not something pulled from the minor), and compute the sign with a simple parity test ((i % 2) ? -1 : 1) instead of pow.
  • Allocate minor correctly (e.g. malloc(sizeof(Matrix)) or declare it on the stack and pass &minor to your helper), check malloc results, and free any heap memory. Implement clear base cases for order 1 and 2 (and optionally 3) to stop recursion cleanly.

Additional notes: keep printing out of tight recursion (use a debug flag), run the code under Valgrind to catch leaks/invalid accesses, and remember Laplace expansion is exponential. For anything beyond small matrices, switch to an LU (Gaussian elimination with partial pivoting) approach: O(n^3) and far more stable.

Recommended Answers

All 3 Replies

I don't see anything obvious, but I'm not familiar with this, either.

If I were starting to debug it, I'd probably start with assertions to check that all the indices are staying within their proper ranges. Then start checking the subtotals, and whether j=0 is correct, for it's initialization (or should it be j=i?).
Should newmatrix be set to order-1?, etc.

There are lots of examples of this kind of code, but I don't know if it uses the cofactor method or not.

At line 42 you call matrixCofact as if it returns the minor's determinant. I recommend to (a) make matrixCofact return double, (b) get rid of its third parameter (you don't use it anyway), and (c) change line 50 to return det . Of course, det should be just double (not a pointer).
PS: minor->elements at line 52 is wrong. It should be mat->elements[0].
PPS: You probably know that it is one of the least efficient algorithms.

Hello
nezachem really thanks for your guide it was helpful. Another problem of my code is at line 41:

if( minor->colCount > 3)

it should be change to

if( order <3 )

because minor row and col amount is 1 less than order at every step because of this code

newMatrix(order-1,order-1,minor)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.