在C中找到矩阵3x3或更大的行列式的问题

时间:2020-04-03 20:41:19

标签: c

我已经用1x1和2x2矩阵运行了它,但是对于较大的矩阵,我没有得到正确的答案。我在代码中有一个示例5x5矩阵,其行列式应为-30024。

我正在运行此代码,但不会给出正确的答案:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define rMax 5

double a[rMax][rMax] = {{-1,2,3,-6,7}, {-2,0,-1,4,2}, {1,-9,8,2,0}, {9,3,5,7,9}, {-5,3,2,-2,2}};
//determinant should be -30024

double matrix_determinant(size_t rowMax, const double z[][rMax])
{
    double final = 0;
    double w[rowMax][rowMax];

    for(size_t row = 0; row < rowMax; row++) //copies z into a new editable matrix
    {
        for(size_t column = 0; column < rowMax; column++)
            w[row][column] = z[row][column];
    }

    if(rowMax > 2) //checks for larger matrix
    {
        for(size_t mat = 0; mat < rowMax; mat++) //loops equal to the max width of the matrix
        {
            double new[rowMax - 1][rowMax - 1]; //new matrix is 1x1 smaller

            for(size_t cRow = 0; cRow < (rowMax - 1); cRow++) //initializing the new matrix
            {
                for(size_t cCol = 0; cCol < (rowMax - 1); cCol++)
                {
                    new[cRow][cCol] = w[cRow + 1][((cCol + mat) % (rowMax - 1)) + 1];
                }           
            }
            if(0 == (mat % 2)) //alternates adding and subtracting
                final += (w[0][mat] * matrix_determinant((rowMax - 1), new));
            else
                final += ((-1) * w[0][mat] * matrix_determinant((rowMax - 1), new));
        }

        return final;
    }

    if(rowMax == 1) //checks for 1x1 matrix
    {
        return w[0][0];
    }

    else //computes final 2x2 matrix (base case)
    {
        final = (w[0][0] * w[1][1]) - (w[0][1] * w[1][0]);
        return final;
    }
}

int main ( void )
{
    size_t s = rMax;
    double det = matrix_determinant(s, a);
    printf("The determinant of matrix a is: %lf\n", det);
}

1 个答案:

答案 0 :(得分:2)

2个更改。

类型错误

double new[rowMax - 1][rowMax - 1];传递给matrix_determinant(size_t rowMax, const double z[][rMax])是错误的。最后的[rowMax - 1]不一定与[rMax]匹配。

由于各种原因(side issue),我还取出了const

// double matrix_determinant(size_t rowMax,   double z[][rMax])
double matrix_determinant(size_t rowMax,    double z[rowMax][rowMax])

计算错误

重新计算new[cRow][cCol]。 OP的代码未跳过w[][]中的右列。

            size_t offset = 0;
            for(size_t cCol = 0; cCol < (rowMax - 1); cCol++) {
                //new[cRow][cCol] = w[cRow + 1][((cCol + mat) % (rowMax - 1)) + 1];
                if (cCol == mat) offset = 1;
                new[cRow][cCol] = w[cRow + 1][cCol + offset];
            }

结果

The determinant of matrix a is: -30024.000000