Calculating Matrix Determinant with C++ - Eong Koungmeng

Eong Koungmeng - អ៊ឹង គួងម៉េង

Hot

Post Top Ad

Tuesday, 4 October 2022

Calculating Matrix Determinant with C++

About Program

This program can calculate the determinant of any square matrix. I used the STL(std::vector) to store the matrices. To calculate the determinant, I used recursive function concept.

/*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();
}
view raw Determinant.cpp hosted with ❤ by GitHub

The output

No comments:

Post a Comment

Post Top Ad