Search code examples
c++matrixcalculatorinverse

I'm getting error in my c++ code! & How to find determinant and inverse of matrix in c++?


I'm trying make matrix calculator. in which i almost done every operation which required in matrix. So now i'm trying to code to find determinant and inverse of matrix, but im getting error like :- argument of type "int" is incompatible with parameter of type "double(*)[100]"

I'm using Visual Studio 2019.
int dat(int n, double mat[100][100]) //function
{
    Matrix s1;
    double det = 0;
    int p, r, c, subi, i, j, subj;
    int submat[10][10];
    s1.getmatrix1();
    r = c = n;
    if (n == 2)
        return((mat[0][0] * mat[1][1]) * (mat[1][0] * mat[0][1]));
    else
    {
        for (p = 0; p < n; p++)
        {
            subi = 0;
            for (i = 0; i < n; i++)
            {
                subj = 0;
                for (j = 0; j < n; j++)
                {
                    if (j == c)
                        continue;
                    submat[subi][subj] = mat[i][j];
                    subj++;
                }
                subi++;
            }
            det = det + (pow(-1, p) * mat[0][p] * dat(n - 1, submat[i][j])); //here at 'submat' i'm getting that error. 
        }
    }
    return 0;
};

Solution

  • There are a couple of problems with your code beside the compilation error.

    1) Since dat expects the second argument to be an array, the function call should be:

    det = det + (pow(-1, p) * mat[0][p] * dat(n - 1, submat));
    

    2) The determinant of a 2x2 matrix should be computed as follows:

    return((mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1]));
    

    3) int submat[10][10] should be double submat[100][100] since it needs to be able to contain (almost) as many elements as mat and should store the same data type.

    4) The return value should be double instead of int.

    5) The condition if (j == c) should be if (j == p) since p is the row/column that we want to exclude.

    6) The i loop should start at 1 since we do not include the first row/column in the submatrix.

    7) s1, r, and c are never used and can be removed.

    8) The return value should be det

    Note: The time complexity of this algorithm, called Laplace Expansion, is O(n!) (see here). If you want to use it for production code, I strongly recommend using a more efficient algorithm that are based on matrix decomposition.