求四阶矩阵的逆矩阵C语言代码
时间: 2024-01-13 07:12:17 浏览: 93
以下是求解4阶矩阵逆矩阵的C语言代码:
```c
#include <stdio.h>
#define N 4
void printMatrix(float matrix[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%.2f ", matrix[i][j]);
}
printf("\n");
}
}
void getCofactor(float matrix[N][N], float temp[N][N], 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++;
}
}
}
}
}
float determinant(float matrix[N][N], int n) {
float det = 0;
if (n == 1) {
return matrix[0][0];
}
float temp[N][N];
int sign = 1;
for (int i = 0; i < n; i++) {
getCofactor(matrix, temp, 0, i, n);
det += sign * matrix[0][i] * determinant(temp, n - 1);
sign = -sign;
}
return det;
}
void adjoint(float matrix[N][N], float adj[N][N]) {
if (N == 1) {
adj[0][0] = 1;
return;
}
int sign = 1;
float temp[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
getCofactor(matrix, temp, i, j, N);
sign = ((i + j) % 2 == 0) ? 1 : -1;
adj[j][i] = sign * determinant(temp, N - 1);
}
}
}
int inverse(float matrix[N][N], float inv[N][N]) {
float det = determinant(matrix, N);
if (det == 0) {
printf("Matrix is singular and has no inverse\n");
return 0;
}
float adj[N][N];
adjoint(matrix, adj);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
inv[i][j] = adj[i][j] / det;
}
}
return 1;
}
int main() {
float matrix[N][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
float inv[N][N];
if (inverse(matrix, inv)) {
printf("Inverse of the matrix:\n");
printMatrix(inv);
}
return 0;
}
```
该代码实现了矩阵的求行列式、伴随矩阵、逆矩阵,其中逆矩阵的计算是通过将伴随矩阵除以行列式得到的。在 main 函数中,我们可以将需要求逆矩阵的矩阵存储在一个二维数组中,然后调用 inverse 函数来求解逆矩阵。如果矩阵是奇异的,即行列式为零,那么逆矩阵不存在。
阅读全文