행렬 역행렬 계산
이제 행렬의 행렬식과 수반 행렬을 모두 계산하는 함수를 구현했으므로, 마침내 행렬의 역행렬을 계산할 수 있습니다. 앞서 언급했듯이, 역행렬을 구하는 공식은 다음과 같습니다:
역행렬 (A) = 수반 행렬 (A) / 행렬식 (A)
이 마지막 단계에서는 다음을 수행합니다:
- 행렬 역변환 함수를 구현합니다.
- 행렬을 읽고 역행렬을 계산하는 완전한 프로그램을 만듭니다.
- 가독성을 높이기 위해 향상된 출력 형식을 추가합니다.
이 마지막 단계를 위해 새 파일을 만들어 봅시다:
~/project 디렉토리에 matrix_inverse.c라는 새 파일을 만듭니다.
다음 코드를 파일에 복사합니다:
#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;
}
이 코드의 주요 새 구성 요소에 대해 알아봅시다:
행렬 역변환 이해:
행렬 A 에 대해, 역행렬 A^(-1) 은 방정식 A × A^(-1) = A^(-1) × A = I 를 만족합니다. 여기서 I 는 항등 행렬입니다.
우리가 사용하는 공식은 다음과 같습니다: A^(-1) = adj(A) / det(A)
이제 프로그램을 컴파일하고 실행해 봅시다:
-
다음 명령으로 프로그램을 컴파일합니다:
cd ~/project
gcc matrix_inverse.c -o matrix_inverse
-
프로그램을 실행합니다:
./matrix_inverse
다음과 유사한 출력을 볼 수 있습니다:
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
결과를 확인해 봅시다: 원래 행렬과 역행렬의 곱은 항등 행렬에 매우 가까워야 합니다. 작은 행렬의 경우 수동으로 확인할 수 있습니다.
2×2 예제를 위해 다음을 시도해 봅시다:
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
2×2 행렬의 경우, 다음 공식을 사용하여 역행렬을 쉽게 확인할 수 있습니다:
행렬 A = [[a, b], [c, d]]의 경우, 역행렬은 다음과 같습니다:
A^(-1) = (1/det(A)) × [[d, -b], [-c, a]]
여기서 det(A) = a×d - b×c
예제에서:
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]]
축하합니다! 이제 C 로 완전한 행렬 역행렬 계산기를 성공적으로 구현했습니다.