Computing the Matrix Inverse
Now that we have implemented functions to calculate both the determinant and adjoint of a matrix, we can finally compute the inverse of a matrix. As mentioned earlier, the formula for finding the inverse is:
Inverse(A) = Adjoint(A) / Determinant(A)
In this final step, we will:
- Implement the matrix inversion function
- Create a complete program that reads a matrix and calculates its inverse
- Add enhanced output formatting for better readability
Let us create a new file for this final step:
- Create a new file named
matrix_inverse.c
in the ~/project
directory
Copy the following code into the file:
#include <stdio.h>
#define MAX_SIZE 10
// Function to read matrix elements from user
void readMatrix(int matrix[MAX_SIZE][MAX_SIZE], int size) {
printf("Enter the elements of the %dx%d matrix:\n", size, size);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
}
// Function to get cofactor of matrix[p][q] in temp[][]
void getCofactor(int matrix[MAX_SIZE][MAX_SIZE], int temp[MAX_SIZE][MAX_SIZE],
int p, int q, int n) {
int i = 0, j = 0;
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
if (row != p && col != q) {
temp[i][j++] = matrix[row][col];
if (j == n - 1) {
j = 0;
i++;
}
}
}
}
}
// Recursive function to find determinant of matrix
int determinant(int matrix[MAX_SIZE][MAX_SIZE], int n) {
int det = 0;
if (n == 1)
return matrix[0][0];
int temp[MAX_SIZE][MAX_SIZE];
int sign = 1;
for (int f = 0; f < n; f++) {
getCofactor(matrix, temp, 0, f, n);
det += sign * matrix[0][f] * determinant(temp, n - 1);
sign = -sign;
}
return det;
}
// Function to calculate the adjoint of a matrix
void adjoint(int matrix[MAX_SIZE][MAX_SIZE], int adj[MAX_SIZE][MAX_SIZE], int n) {
if (n == 1) {
adj[0][0] = 1;
return;
}
int sign = 1;
int temp[MAX_SIZE][MAX_SIZE];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Get cofactor of matrix[i][j]
getCofactor(matrix, temp, i, j, n);
// Sign of adj[j][i] positive if sum of row and column indices is even
sign = ((i + j) % 2 == 0) ? 1 : -1;
// Interchanging rows and columns to get the transpose of the cofactor matrix
adj[j][i] = sign * determinant(temp, n - 1);
}
}
}
// Function to calculate the inverse of a matrix
int inverse(int matrix[MAX_SIZE][MAX_SIZE], float inverse[MAX_SIZE][MAX_SIZE], int n) {
// Find determinant of matrix
int det = determinant(matrix, n);
// If determinant is zero, matrix is not invertible
if (det == 0) {
printf("Matrix is not invertible as determinant is zero.\n");
return 0;
}
// Find adjoint of matrix
int adj[MAX_SIZE][MAX_SIZE];
adjoint(matrix, adj, n);
// Find inverse by dividing adjoint by determinant
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
inverse[i][j] = adj[i][j] / (float)det;
}
}
return 1;
}
// Function to display an integer matrix
void displayMatrix(int matrix[MAX_SIZE][MAX_SIZE], int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
// Function to display a float matrix (for inverse)
void displayFloatMatrix(float matrix[MAX_SIZE][MAX_SIZE], int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("%.4f\t", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int matrix[MAX_SIZE][MAX_SIZE];
float inv[MAX_SIZE][MAX_SIZE];
int size;
// Get matrix size from user
printf("Matrix Inverse Calculator\n");
printf("=========================\n");
printf("Enter the size of the square matrix (1-%d): ", MAX_SIZE);
scanf("%d", &size);
// Validate matrix size
if (size <= 0 || size > MAX_SIZE) {
printf("Invalid matrix size. Please enter a size between 1 and %d.\n", MAX_SIZE);
return 1;
}
// Read matrix elements
readMatrix(matrix, size);
// Display the original matrix
printf("\nOriginal Matrix:\n");
displayMatrix(matrix, size);
// Calculate and display the determinant
int det = determinant(matrix, size);
printf("\nDeterminant of the matrix is: %d\n", det);
// Calculate and display the inverse
if (inverse(matrix, inv, size)) {
printf("\nInverse Matrix:\n");
displayFloatMatrix(inv, size);
}
return 0;
}
Let us understand the key new components of this code:
-
inverse()
- This function calculates the inverse of a matrix by:
- Finding the determinant
- Checking if the determinant is non-zero (invertible)
- Calculating the adjoint
- Dividing each element of the adjoint by the determinant
-
displayFloatMatrix()
- A new function to display the inverse matrix with floating-point precision, since the inverse elements are not necessarily integers.
Understanding Matrix Inversion:
For a matrix A, the inverse A^(-1) satisfies the equation: A × A^(-1) = A^(-1) × A = I, where I is the identity matrix.
The formula we're using is: A^(-1) = adj(A) / det(A)
Now, let us compile and run our program:
- Compile the program with the following command:
cd ~/project
gcc matrix_inverse.c -o matrix_inverse
- Run the program:
./matrix_inverse
You should see output similar to this:
Matrix Inverse Calculator
=========================
Enter the size of the square matrix (1-10): 3
Enter the elements of the 3x3 matrix:
Enter element [0][0]: 4
Enter element [0][1]: 3
Enter element [0][2]: 1
Enter element [1][0]: 0
Enter element [1][1]: -1
Enter element [1][2]: 2
Enter element [2][0]: -3
Enter element [2][1]: 3
Enter element [2][2]: 1
Original Matrix:
4 3 1
0 -1 2
-3 3 1
Determinant of the matrix is: 37
Inverse Matrix:
0.0270 0.1351 -0.1351
0.2432 -0.0541 -0.2432
-0.1081 0.4865 0.1081
Let us verify the result: The product of the original matrix and its inverse should be very close to the identity matrix. You can verify this manually for small matrices.
For a 2×2 example, let us try:
Matrix Inverse Calculator
=========================
Enter the size of the square matrix (1-10): 2
Enter the elements of the 2x2 matrix:
Enter element [0][0]: 4
Enter element [0][1]: 7
Enter element [1][0]: 2
Enter element [1][1]: 6
Original Matrix:
4 7
2 6
Determinant of the matrix is: 10
Inverse Matrix:
0.6000 -0.7000
-0.2000 0.4000
For a 2×2 matrix, you can easily verify the inverse using the formula:
For matrix A = [[a, b], [c, d]], the inverse is:
A^(-1) = (1/det(A)) × [[d, -b], [-c, a]]
where det(A) = a×d - b×c
In our example:
det(A) = 4×6 - 7×2 = 24 - 14 = 10
A^(-1) = (1/10) × [[6, -7], [-2, 4]] = [[0.6, -0.7], [-0.2, 0.4]]
Congratulations! You have now successfully implemented a complete matrix inverse calculator in C.