C Online Compiler
Example: Inverse of a 3x3 Matrix in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Inverse of a 3x3 Matrix #include <stdio.h> #include <stdlib.h> // For exit() // Function to display a 3x3 matrix void displayMatrix(double mat[3][3]) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("%10.4f ", mat[i][j]); } printf("\n"); } printf("\n"); } // Function to calculate the determinant of a 2x2 matrix double determinant2x2(double a, double b, double c, double d) { return a * d - b * c; } // Function to calculate the determinant of a 3x3 matrix double determinant3x3(double mat[3][3]) { double det = 0; // Formula for 3x3 determinant: // a(ei - fh) - b(di - fg) + c(dh - eg) det = mat[0][0] * determinant2x2(mat[1][1], mat[1][2], mat[2][1], mat[2][2]) - mat[0][1] * determinant2x2(mat[1][0], mat[1][2], mat[2][0], mat[2][2]) + mat[0][2] * determinant2x2(mat[1][0], mat[1][1], mat[2][0], mat[2][1]); return det; } // Function to find the inverse of a 3x3 matrix void findInverse(double mat[3][3], double inverseMat[3][3]) { double det = determinant3x3(mat); // Check if determinant is zero (matrix is singular) if (det == 0) { printf("Determinant is 0, inverse does not exist for this matrix.\n"); exit(EXIT_FAILURE); } double adj[3][3]; // Adjoint matrix double cofactor[3][3]; // Cofactor matrix (will be transposed to form adjoint) // Calculate cofactor matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { // Create a temporary 2x2 submatrix double submatrix[2][2]; int r = 0, c = 0; for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { if (row != i && col != j) { submatrix[r][c++] = mat[row][col]; if (c == 2) { c = 0; r++; } } } } // Calculate determinant of 2x2 submatrix and apply sign cofactor[i][j] = determinant2x2(submatrix[0][0], submatrix[0][1], submatrix[1][0], submatrix[1][1]); if ((i + j) % 2 == 1) { // If (i+j) is odd, multiply by -1 cofactor[i][j] = -cofactor[i][j]; } } } // Transpose the cofactor matrix to get the adjoint matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { adj[j][i] = cofactor[i][j]; // Note: adj[j][i] = cofactor[i][j] for transpose } } // Calculate the inverse matrix (adjugate / determinant) for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { inverseMat[i][j] = adj[i][j] / det; } } } int main() { // Step 1: Initialize the 3x3 matrix double matrix[3][3] = { {1, 2, 3}, {0, 1, 4}, {5, 6, 0} }; double inverse[3][3]; // Step 2: Display the original matrix printf("Original 3x3 Matrix:\n"); displayMatrix(matrix); // Step 3: Find and display the inverse matrix findInverse(matrix, inverse); printf("Inverse of the 3x3 Matrix:\n"); displayMatrix(inverse); return 0; }
Output
Clear
ADVERTISEMENTS