C++ Online Compiler
Example: Inverse of a 2x2 Matrix using Adjoint Method in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Inverse of a 2x2 Matrix using Adjoint Method #include <iostream> #include <vector> #include <iomanip> // For std::fixed and std::setprecision using namespace std; // Function to calculate the determinant of a 2x2 matrix double determinant2x2(const vector<vector<double>>& matrix) { return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; } int main() { // Step 1: Define the 2x2 matrix vector<vector<double>> matrix = { {3, 4}, {1, 2} }; cout << "Original Matrix:" << endl; for (const auto& row : matrix) { for (double val : row) { cout << val << " "; } cout << endl; } cout << endl; // Step 2: Calculate the determinant double det = determinant2x2(matrix); if (det == 0) { cout << "Determinant is 0. Inverse does not exist." << endl; return 0; } // Step 3: Calculate the adjoint matrix (for a 2x2 matrix, this is simpler) // adj(A) = | d -b | // | -c a | // where A = | a b | // | c d | vector<vector<double>> adjoint(2, vector<double>(2)); adjoint[0][0] = matrix[1][1]; adjoint[0][1] = -matrix[0][1]; adjoint[1][0] = -matrix[1][0]; adjoint[1][1] = matrix[0][0]; // Step 4: Calculate the inverse matrix vector<vector<double>> inverse(2, vector<double>(2)); double inv_det = 1.0 / det; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { inverse[i][j] = inv_det * adjoint[i][j]; } } // Step 5: Print the inverse matrix cout << "Inverse Matrix:" << endl; cout << fixed << setprecision(2); // Format output to 2 decimal places for (const auto& row : inverse) { for (double val : row) { cout << val << " "; } cout << endl; } return 0; }
Output
Clear
ADVERTISEMENTS