C Program To Find Inverse Of A 3x3 Matrix
In this article, you will learn how to write a C program to find the inverse of a 3x3 matrix using the determinant and adjoint method.
Problem Statement
Matrix inversion is a fundamental operation in linear algebra, especially for square matrices. The inverse of a matrix, if it exists, is another matrix that, when multiplied by the original matrix, yields the identity matrix. For a 3x3 matrix, finding its inverse involves several steps: calculating the determinant, finding the matrix of cofactors, transposing it to get the adjoint matrix, and finally dividing the adjoint by the determinant. This process can be mathematically intensive to perform manually, making a programmatic solution highly valuable.
Example
Consider the following 3x3 matrix:
{{1, 2, 3},
{0, 1, 4},
{5, 6, 0}}
Its inverse, calculated programmatically, will be:
{{-24, 18, 5},
{20, -15, -4},
{-5, 4, 1}}
(Note: This inverse is simplified for presentation, typically it would involve fractions if the determinant isn't 1.)
Background & Knowledge Prerequisites
To understand and implement the solution, you should have a basic understanding of:
- Linear Algebra Concepts:
- Determinant: A scalar value that can be computed from the elements of a square matrix. A matrix is invertible if and only if its determinant is non-zero.
- Cofactor: The cofactor of an element
a_ijin a matrix is(-1)^(i+j)times the determinant of the submatrix obtained by deleting rowiand columnj. - Adjoint Matrix: The transpose of the cofactor matrix.
- Inverse Matrix: For a matrix
A, its inverseA^-1is given byA^-1 = (1 / det(A)) * adj(A). - C Programming Basics:
- Arrays (specifically 2D arrays for matrices).
- Functions and function calls.
- Conditional statements (
if-else). - Loops (
forloops). - Floating-point numbers (
doublefor precision).
Use Cases
Finding the inverse of a matrix is a critical operation with numerous applications across various fields:
- Solving Systems of Linear Equations: The most common application. For
Ax = B, ifAis invertible, thenx = A^-1 * B. - Computer Graphics: Used for transformations like scaling, rotation, and translation, especially for reversing transformations.
- Cryptography: Involved in certain encryption and decryption algorithms.
- Statistics and Econometrics: Used in regression analysis to estimate parameters.
- Robotics: For calculating joint angles and positions in robotic kinematics.
Solution Approaches
For a 3x3 matrix, the standard and most direct approach involves the calculation of its determinant and adjoint matrix. There isn't a significantly different "approach" for this specific problem size that avoids these core steps without resorting to more complex numerical methods (like Gaussian elimination, which is typically for larger matrices or solving Ax=B directly).
Inverse of a 3x3 Matrix using Determinant and Adjoint
This approach calculates the determinant of the 3x3 matrix, then finds the cofactor matrix, transposes it to get the adjoint, and finally divides the adjoint matrix by the determinant to obtain the inverse.
Code Example
// 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;
}
Sample Output
Original 3x3 Matrix:
1.0000 2.0000 3.0000
0.0000 1.0000 4.0000
5.0000 6.0000 0.0000
Inverse of the 3x3 Matrix:
-24.0000 18.0000 5.0000
20.0000 -15.0000 -4.0000
-5.0000 4.0000 1.0000
Stepwise Explanation
displayMatrix(double mat[3][3]): A utility function to print a 3x3 matrix to the console in a formatted way.determinant2x2(double a, double b, double c, double d): A helper function to compute the determinant of a simple 2x2 matrix, used in the 3x3 determinant calculation and for cofactors.determinant3x3(double mat[3][3]):- This function calculates the determinant of the input 3x3 matrix directly using the expansion by minors along the first row.
determinant2x2 function for the 2x2 sub-determinants.findInverse(double mat[3][3], double inverseMat[3][3]): This is the core function.- It first calls
determinant3x3to get the determinant of the input matrix.
- It first calls
mat[i][j] of the original matrix. For each element, it constructs a temporary 2x2 submatrix by excluding the current row i and column j. It then calculates the determinant of this 2x2 submatrix. This result is multiplied by (-1)^(i+j) to get the cofactor cofactor[i][j].adj is the transpose of the cofactor matrix. This means adj[j][i] = cofactor[i][j].adj matrix is divided by the det (calculated earlier) to form the inverseMat.main()Function:- Declares and initializes a sample 3x3 matrix.
displayMatrix to show the original matrix.findInverse to compute the inverse and store it in the inverse array.displayMatrix again to show the resulting inverse matrix.Conclusion
Finding the inverse of a 3x3 matrix is a fundamental operation in linear algebra with wide-ranging applications. By understanding the mathematical principles of determinants, cofactors, and adjoints, we can implement a robust C program to perform this calculation efficiently. The provided solution demonstrates a clear, step-by-step approach using functions to modularize the logic, ensuring readability and maintainability.
Summary
- The inverse of a matrix
A(denotedA^-1) satisfiesA * A^-1 = I, whereIis the identity matrix. - A matrix must be square and have a non-zero determinant to be invertible (non-singular).
- The process involves calculating the determinant of the 3x3 matrix.
- Next, a cofactor matrix is formed by finding the determinant of 2x2 submatrices and applying appropriate signs.
- The adjoint matrix is obtained by transposing the cofactor matrix.
- The inverse is then found by dividing each element of the adjoint matrix by the determinant of the original matrix.
- This C program provides a practical implementation for this common mathematical task.