[英]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). 我编写的函数没有任何参数(因为它是类中的一个函数,因此矩阵由“ this->”命令定义)。 So the minimum case I guess it is when a matrix 2x2 can be solved.
所以我猜最小的情况是矩阵2x2可以求解的时候。 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.
在这种情况下,在矩阵3x3中,可以通过将第一个元素乘以2x2的行列式(2x2 * 3x3-2x3 * 3x2)来解决,但是当然它必须递归地执行...您不能只写那些价值观。
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. 主要问题是,只要该代码以3x3运行,您就在3x3上调用calcularDeterminante()。
in the loop of your else statement, you should be creating the three 2x2 'sub' matrix and then call calcularDeterminante() on them. 在else语句的循环中,应该创建三个2x2的“子”矩阵,然后在它们上调用calcularDeterminante()。 Personally I'd introduce a helper method that retrieves theses submatrix given a row,column.
我个人将介绍一种辅助方法,该方法在给定行,列的情况下检索这些子矩阵。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.