C 언어로 행렬 역행렬 계산하기

CBeginner
지금 연습하기

소개

이 랩에서는 C 프로그래밍을 사용하여 정사각 행렬의 역행렬을 계산하는 방법을 배웁니다. 행렬의 역행렬은 선형 대수학에서 중요한 개념으로, 선형 방정식 시스템 해결, 컴퓨터 그래픽, 데이터 분석, 그리고 많은 과학 컴퓨팅 분야에서 응용됩니다.

사용자 입력을 통해 정사각 행렬을 읽고, 행렬의 행렬식 (determinant) 과 수반 행렬 (adjoint) 을 계산한 다음, 이러한 값을 사용하여 역행렬을 계산하는 과정을 탐구할 것입니다. 이 랩에서는 이러한 수학적 연산을 C 코드로 구현하는 실질적인 경험을 제공하여 프로그래밍 개념과 선형 대수학 원리에 대한 이해를 강화합니다.

이 랩을 마치면 완전한 행렬 역행렬 프로그램을 구현하고, 그 과정에 관련된 기본적인 수학적 기법을 이해할 수 있게 될 것입니다.

사용자 입력을 통해 정사각 행렬 읽기

이 단계에서는 사용자 입력을 통해 정사각 행렬을 읽는 프로그램을 만들 것입니다. 정사각 행렬은 행과 열의 수가 동일하며, 이는 행렬 역행렬을 계산하는 데 필요한 조건입니다.

먼저, 우리가 해야 할 일을 이해해 봅시다:

  1. 행렬의 최대 크기를 정의합니다.
  2. 사용자로부터 실제 행렬 크기를 얻습니다.
  3. 행렬의 각 요소를 읽습니다.
  4. 입력을 확인하기 위해 행렬을 표시합니다.

프로젝트 디렉토리에 새로운 C 파일을 만들어 시작해 봅시다:

  1. WebIDE 를 열고 프로젝트 디렉토리로 이동합니다.
  2. ~/project 디렉토리에 matrix_input.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 display the matrix
void displayMatrix(int matrix[MAX_SIZE][MAX_SIZE], int size) {
    printf("\nMatrix Contents:\n");
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int matrix[MAX_SIZE][MAX_SIZE];
    int size;

    // Get matrix size from user
    printf("Matrix Input Program\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 matrix
    displayMatrix(matrix, size);

    return 0;
}

이 코드의 주요 구성 요소를 이해해 봅시다:

  • #define MAX_SIZE 10 - 이것은 최대 행렬 크기에 대한 상수를 정의합니다.
  • readMatrix() - 중첩 루프를 사용하여 행렬의 각 요소를 읽는 함수입니다.
  • displayMatrix() - 행렬을 표 형식으로 출력하는 함수입니다.
  • main() 함수에서 사용자로부터 크기를 얻고 행렬을 읽기 전에 유효성을 검사합니다.

이제 프로그램을 컴파일하고 실행해 봅시다:

  1. WebIDE 에서 터미널을 엽니다.

  2. 다음 명령으로 프로그램을 컴파일합니다:

    cd ~/project
    gcc matrix_input.c -o matrix_input
  3. 프로그램을 실행합니다:

    ./matrix_input

다음과 유사한 출력을 볼 수 있습니다:

Matrix Input Program
====================
Enter the size of the square matrix (1-10): 3
Enter the elements of the 3x3 matrix:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 4
Enter element [1][1]: 5
Enter element [1][2]: 6
Enter element [2][0]: 7
Enter element [2][1]: 8
Enter element [2][2]: 9

Matrix Contents:
1	2	3
4	5	6
7	8	9

이제 사용자 입력을 통해 정사각 행렬을 읽고 표시하는 프로그램을 성공적으로 만들었습니다. 이것은 행렬 역행렬 계산 과정의 첫 번째 단계입니다.

행렬식 (Determinant) 및 여인자 (Cofactor) 계산

행렬의 역행렬을 계산하기 전에, 두 가지 핵심 수학적 연산, 즉 행렬의 행렬식과 여인자를 이해하고 구현해야 합니다. 행렬식은 정사각 행렬에서 파생된 스칼라 값이며, 행렬이 가역적인지 여부를 결정하는 데 중요한 역할을 합니다.

이 단계에서는 다음을 수행합니다:

  1. 행렬식과 여인자가 무엇인지 배웁니다.
  2. 이를 계산하는 함수를 구현합니다.
  3. 간단한 행렬로 구현을 테스트합니다.

이 단계를 위해 새 파일을 만들어 봅시다:

  1. ~/project 디렉토리에 matrix_determinant.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;

    // Looping for each element of the matrix
    for (int row = 0; row < n; row++) {
        for (int col = 0; col < n; col++) {
            // Copying into temporary matrix only those elements
            // which are not in given row and column
            if (row != p && col != q) {
                temp[i][j++] = matrix[row][col];

                // Row is filled, so increase row index and
                // reset column index
                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; // Initialize result

    // Base case: if matrix contains single element
    if (n == 1)
        return matrix[0][0];

    int temp[MAX_SIZE][MAX_SIZE]; // To store cofactors
    int sign = 1; // To store sign multiplier

    // Iterate for each element of first row
    for (int f = 0; f < n; f++) {
        // Getting cofactor of matrix[0][f]
        getCofactor(matrix, temp, 0, f, n);

        // Adding to determinant with appropriate sign
        det += sign * matrix[0][f] * determinant(temp, n - 1);

        // Alternating sign factor
        sign = -sign;
    }

    return det;
}

// Function to display the matrix
void displayMatrix(int matrix[MAX_SIZE][MAX_SIZE], int size) {
    printf("\nMatrix Contents:\n");
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int matrix[MAX_SIZE][MAX_SIZE];
    int size;

    // Get matrix size from user
    printf("Matrix Determinant 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 matrix
    displayMatrix(matrix, size);

    // Calculate and display the determinant
    int det = determinant(matrix, size);
    printf("\nDeterminant of the matrix is: %d\n", det);

    // Check if matrix is invertible
    if (det == 0) {
        printf("The matrix is not invertible (determinant is zero).\n");
    } else {
        printf("The matrix is invertible (determinant is non-zero).\n");
    }

    return 0;
}

이 코드의 주요 구성 요소를 이해해 봅시다:

  • getCofactor() - 이 함수는 특정 행과 열을 제거하여 부분 행렬을 추출합니다. 이는 행렬식과 수반 행렬을 계산하는 데 필수적입니다.
  • determinant() - 여인자 전개 방법을 사용하여 행렬의 행렬식을 계산하는 재귀 함수입니다.
  • 또한 행렬식이 0 이 아닌지 테스트하여 행렬이 가역적인지 확인합니다.

수학적 개념 이해:

  1. 여인자 (Cofactor): 행렬의 각 요소에 대해, 여인자는 해당 요소의 행과 열을 제거하여 형성된 부분 행렬의 행렬식에 (-1)^(i+j) 를 곱한 값입니다. 여기서 i, j 는 행과 열의 인덱스입니다.

  2. 행렬식 (Determinant): 행렬식은 정사각 행렬에서 계산된 특수한 숫자입니다. 2×2 행렬 [[a,b],[c,d]]의 경우, 행렬식은 (a×d - b×c) 입니다. 더 큰 행렬의 경우, 여인자 전개를 사용합니다.

  3. 가역성 (Invertibility): 행렬은 행렬식이 0 이 아닌 경우에만 가역적입니다.

이제 프로그램을 컴파일하고 실행해 봅시다:

  1. 다음 명령으로 프로그램을 컴파일합니다:

    cd ~/project
    gcc matrix_determinant.c -o matrix_determinant
  2. 프로그램을 실행합니다:

    ./matrix_determinant

다음과 유사한 출력을 볼 수 있습니다:

Matrix Determinant Calculator
=============================
Enter the size of the square matrix (1-10): 3
Enter the elements of the 3x3 matrix:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 0
Enter element [1][1]: 1
Enter element [1][2]: 4
Enter element [2][0]: 5
Enter element [2][1]: 6
Enter element [2][2]: 0

Matrix Contents:
1	2	3
0	1	4
5	6	0

Determinant of the matrix is: 49
The matrix is invertible (determinant is non-zero).

행렬식이 0 인 행렬을 포함하여 다양한 행렬을 입력하여 프로그램의 동작을 확인해 보세요. 예를 들어, 한 행이 다른 행의 배수인 행렬을 입력하면 행렬식은 0 이 됩니다.

이제 행렬의 역행렬을 찾는 데 중요한 구성 요소인 행렬식 계산을 성공적으로 구현했습니다.

행렬의 수반 행렬 (Adjoint) 계산

행렬 역행렬을 계산하는 다음 단계는 행렬의 수반 행렬 (adjoint, 또는 adjugate 라고도 함) 을 계산하는 것입니다. 행렬의 수반 행렬은 여인자 행렬의 전치 행렬입니다. 수반 행렬과 행렬식을 구하면 다음 공식을 사용하여 역행렬을 계산할 수 있습니다:

역행렬 (A) = 수반 행렬 (A) / 행렬식 (A)

이 단계에서는 다음을 수행합니다:

  1. 수반 행렬 계산 함수를 구현합니다.
  2. 최종 행렬 역변환을 위해 이전 코드를 기반으로 구축합니다.

이 단계를 위해 새 파일을 만들어 봅시다:

  1. ~/project 디렉토리에 matrix_adjoint.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 display the 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");
    }
}

int main() {
    int matrix[MAX_SIZE][MAX_SIZE];
    int adj[MAX_SIZE][MAX_SIZE];
    int size;

    // Get matrix size from user
    printf("Matrix Adjoint 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 the adjoint
    adjoint(matrix, adj, size);

    // Display the adjoint matrix
    printf("\nAdjoint Matrix:\n");
    displayMatrix(adj, size);

    // Calculate and display the determinant
    int det = determinant(matrix, size);
    printf("\nDeterminant of the matrix is: %d\n", det);

    return 0;
}

이 코드의 주요 새 구성 요소에 대해 알아봅시다:

  • adjoint() - 이 함수는 행렬의 수반 행렬을 계산합니다. 이는 여인자 행렬의 전치 행렬입니다. 행렬의 각 요소 (i,j) 에 대해 다음을 수행합니다:
    1. 행 i 와 열 j 를 제거하여 여인자 행렬을 찾습니다.
    2. 이 여인자 행렬의 행렬식을 계산합니다.
    3. 적절한 부호 ((−1)^(i+j)) 를 적용합니다.
    4. 이 값을 수반 행렬의 (j,i) 위치에 배치합니다 (전치).

수반 행렬 계산 이해:

행렬 A 의 수반 행렬 (또는 adjugate) 은 adj(A) 로 표시됩니다. 2×2 행렬의 경우:

A = [a b]
    [c d]

수반 행렬은 다음과 같습니다:

adj(A) = [ d  -b]
         [-c   a]

더 큰 행렬의 경우, 각 요소의 여인자를 계산한 다음 결과 행렬을 전치합니다.

이제 프로그램을 컴파일하고 실행해 봅시다:

  1. 다음 명령으로 프로그램을 컴파일합니다:

    cd ~/project
    gcc matrix_adjoint.c -o matrix_adjoint
  2. 프로그램을 실행합니다:

    ./matrix_adjoint

다음과 유사한 출력을 볼 수 있습니다:

Matrix Adjoint Calculator
=========================
Enter the size of the square matrix (1-10): 3
Enter the elements of the 3x3 matrix:
Enter element [0][0]: 1
Enter element [0][1]: 0
Enter element [0][2]: 2
Enter element [1][0]: 3
Enter element [1][1]: 0
Enter element [1][2]: 4
Enter element [2][0]: 5
Enter element [2][1]: 0
Enter element [2][2]: 6

Original Matrix:
1	0	2
3	0	4
5	0	6

Adjoint Matrix:
0	0	0
-8	-4	4
0	0	0

Determinant of the matrix is: 0

이 예제에서 행렬식이 0 이므로 행렬이 가역적이지 않다는 것을 알 수 있습니다. 가역 행렬의 다른 예를 시도해 봅시다:

Matrix Adjoint Calculator
=========================
Enter the size of the square matrix (1-10): 3
Enter the elements of the 3x3 matrix:
Enter element [0][0]: 5
Enter element [0][1]: -2
Enter element [0][2]: 2
Enter element [1][0]: 1
Enter element [1][1]: 0
Enter element [1][2]: 3
Enter element [2][0]: 3
Enter element [2][1]: 1
Enter element [2][2]: 4

Original Matrix:
5	-2	2
1	0	3
3	1	4

Adjoint Matrix:
-3	11	-5
13	14	-11
-1	-7	2

Determinant of the matrix is: 15

이 경우 행렬식은 15(0 이 아님) 이므로 이 행렬의 역행렬을 계산할 수 있습니다. 이제 행렬 역변환의 마지막 단계인 수반 행렬 계산을 성공적으로 구현했습니다.

행렬 역행렬 계산

이제 행렬의 행렬식과 수반 행렬을 모두 계산하는 함수를 구현했으므로, 마침내 행렬의 역행렬을 계산할 수 있습니다. 앞서 언급했듯이, 역행렬을 구하는 공식은 다음과 같습니다:

역행렬 (A) = 수반 행렬 (A) / 행렬식 (A)

이 마지막 단계에서는 다음을 수행합니다:

  1. 행렬 역변환 함수를 구현합니다.
  2. 행렬을 읽고 역행렬을 계산하는 완전한 프로그램을 만듭니다.
  3. 가독성을 높이기 위해 향상된 출력 형식을 추가합니다.

이 마지막 단계를 위해 새 파일을 만들어 봅시다:

  1. ~/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;
}

이 코드의 주요 새 구성 요소에 대해 알아봅시다:

  • inverse() - 이 함수는 다음을 수행하여 행렬의 역행렬을 계산합니다:

    1. 행렬식을 찾습니다.
    2. 행렬식이 0 이 아닌지 확인합니다 (가역성).
    3. 수반 행렬을 계산합니다.
    4. 수반 행렬의 각 요소를 행렬식으로 나눕니다.
  • displayFloatMatrix() - 역행렬 요소가 반드시 정수가 아니므로 부동 소수점 정밀도로 역행렬을 표시하는 새로운 함수입니다.

행렬 역변환 이해:

행렬 A 에 대해, 역행렬 A^(-1) 은 방정식 A × A^(-1) = A^(-1) × A = I 를 만족합니다. 여기서 I 는 항등 행렬입니다.

우리가 사용하는 공식은 다음과 같습니다: A^(-1) = adj(A) / det(A)

이제 프로그램을 컴파일하고 실행해 봅시다:

  1. 다음 명령으로 프로그램을 컴파일합니다:

    cd ~/project
    gcc matrix_inverse.c -o matrix_inverse
  2. 프로그램을 실행합니다:

    ./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 로 완전한 행렬 역행렬 계산기를 성공적으로 구현했습니다.

요약

이 랩에서는 C 프로그래밍으로 완전한 행렬 역행렬 계산기를 구현했습니다. 랩 전체에서 몇 가지 주요 개념을 탐구하고 단계별로 구현했습니다:

  1. 사용자 입력을 통해 정사각 행렬을 읽고 표시하는 프로그램을 만들어 C 에서 2 차원 배열을 처리하는 방법을 배웠습니다.

  2. 그런 다음 여인자 전개 방법을 사용하여 행렬식을 계산했습니다. 이는 행렬 역변환의 기초가 되는 재귀적 접근 방식입니다.

  3. 다음으로, 코드를 기반으로 여인자 행렬의 전치 행렬인 행렬의 수반 행렬 (adjoint) 을 계산했습니다.

  4. 마지막으로, 이러한 모든 구성 요소를 결합하여 공식: 역행렬 = 수반 행렬 / 행렬식을 사용하여 행렬의 역행렬을 계산했습니다.

이러한 수학적 연산은 선형 대수학의 기본이며 컴퓨터 그래픽, 머신 러닝, 선형 방정식 시스템 해결 등 다양한 분야에서 광범위하게 적용됩니다.

구현은 다음과 같은 여러 프로그래밍 개념을 보여주었습니다:

  • 다차원 배열
  • 재귀 함수
  • 정수와 부동 소수점 숫자 간의 형식 변환
  • 함수 모듈성 및 코드 구성
  • 사용자 입력 유효성 검사

이 랩을 완료함으로써 행렬 연산, 특히 행렬 역변환에 대한 수학적 이론과 프로그래밍 구현 모두에 대한 실질적인 경험을 얻었습니다.