简体   繁体   中英

Determinant of a Matrix recursively in c++

I am trying to calculate the determinant of a Matrix recursevily.

The function I wrote does not take any parametres (because its a function in a class, so the matrix is defined by the "this->" command). So the minimum case I guess it is when a matrix 2x2 can be solved. In this case, in a matrix 3x3, it would be solved by multipling the 1st element with determinant of a 2x2 (2x2*3x3 - 2x3*3x2), but of course it has to do it recursevily... You cannot just write those values.

My code at the moment is this one:

int Matriz::calcularDeterminante()
{   
    int numero=0;
    int signo = 1;
    if (n_filas == 1) {
        return (this->matriz[0][0]);
    }
    else if (n_filas == 2) {
        return (this->matriz[0][0] * this->matriz[1][1]) - (this->matriz[0][1] * this->matriz[1][0]);
    }
    else {
        for (int i = 0; i < n_filas; i++) {
            if (signo == 0) {
                numero += -1* matriz[0][i] * calcularDeterminante();
                signo++;
            }
            else if (signo == 1) {
                numero += signo * matriz[0][i] * calcularDeterminante();
                signo--;
            }               
        }
    }
return numero;
}

but the recursive call is just wrong.

The main problem is that whenever that code runs with a 3x3, you call calcularDeterminante() on the 3x3.

in the loop of your else statement, you should be creating the three 2x2 'sub' matrix and then call calcularDeterminante() on them. Personally I'd introduce a helper method that retrieves theses submatrix given a row,column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM