Calculate Determinant of Matrix with C++

calculate determinant

Using recursive concept to calculate determinant

04 Oct 2022

mathc++

Introduction

This is a program to calculate determinant of any square matrix using recursive concepts.

Code

/*Eong Koungmeng 19/9/2022*/
#include<iostream>
#include<vector>
#include <assert.h>


//This function can calculate determinant of any square matrix
float Determinant(std::vector<std::vector<float>>(matrix))
{
    int rows = matrix.size();
    int cols = matrix[0].size();

    assert(rows == cols); //Raise error is rows != cols
    if (rows == 2)
    {
        return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; //2x2 Matrix
    }
    else

        if (rows > 2) //For 3x3 matrix and bigger
        {
            int sign = 1;
            float sum = 0;
            for (int i = 0; i < rows; i++)
            {
                std::vector<std::vector<float>>subMatrix(rows - 1, std::vector<float>(rows - 1)); //Create subMatrix in order to calculate minor
                for (int j = 1; j < rows; j++)
                {
                    bool b = false;
                    for (int k = 0; k < rows; k++)
                    {
                        if (k == i)
                        {
                            b = true;
                            continue;
                        }
                        subMatrix[j - 1][k - b] = matrix[j][k];
                    }
                }
                sum += sign * matrix[0][i] * Determinant(subMatrix);

                sign *= -1;
            }
            return sum;

        }
        else {
            return matrix[0][0];
        }
}

int main()
{
    //Input any matrix here
    std::vector<std::vector<float>>(matrixA) = { {1, 3, 5, 9}, {1, 3, 1, 7}, {4, 3, 9, 7}, {5, 2, 0, 9} };
    std::cout << "The determinant of the matrix is: " << Determinant(matrixA) << std::endl;
    std::cin.get();
}

Result