-2

I have to make a recursive function that calculates the determinant of the matrix by 3x3 heres is my code

public int determinant(int matrix[][]) {
    if (matrix.length == 2) {
        return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
    }
    double sum = 0.0;
    for (int i = 0; i < matrix.getNcols(); i++) {
        sum += changeSign(i) * matrix.getValueAt(0, i) * determinant(createSubMatrix(matrix, 0, i));
    }
    return sum;
}

I need to change the last return to make recursive but i dont know how actually.

2 Answers2

1

This is recursive, because of this line:

sum += changeSign(i) * matrix.getValueAt(0, i) * determinant(createSubMatrix(matrix, 0, i));

Since you're calling the method within itself, it's recursive. This appears to work fine too.

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
1

I have changed and completed your code and this function works for every determinant of any sized matrixes :

public static int det(Matrix matrixGiven){
    if(matrixGiven.size == 1){
        return matrixGiven.data[0][0];
    }
    else if(matrixGiven.size == 2) {
        return (matrixGiven.data[0][0] * matrixGiven.data[1][1]) - (matrixGiven.data[0][1] * matrixGiven.data[1][0]);
    }
    else{
        int sumForDet = 0;
        int plusOrMinusInDet = 1;
        for(int columnInDet = 0; columnInDet < matrixGiven.size; ++columnInDet){
            int[][] smallerMatrixForDet = new int[matrixGiven.size - 1][matrixGiven.size - 1];
            for(int row = 1, rowForSmallerMatrix = 0; row < matrixGiven.size; ++row ){
                for(int column = 0 ,columnForSmallerMatrix = 0; column < matrixGiven.size; ++column){
                    if(column != columnInDet){
                        smallerMatrixForDet[rowForSmallerMatrix][columnForSmallerMatrix] = matrixGiven.data[row][column];
                        ++columnForSmallerMatrix;
                    }
                }
                ++rowForSmallerMatrix;
            }
            sumForDet += plusOrMinusInDet * matrixGiven.data[0][columnInDet] * det(new Matrix(matrixGiven.size-1,smallerMatrixForDet ));
            plusOrMinusInDet *= -1;
        }
        return sumForDet;
    }
}