Calcular a Inversa de uma Matriz em C

CBeginner
Pratique Agora

Introdução

Neste laboratório, aprenderemos como calcular a inversa de uma matriz quadrada usando a linguagem de programação C. A inversa de uma matriz é um conceito importante em álgebra linear, com aplicações na resolução de sistemas de equações lineares, computação gráfica, análise de dados e muitos domínios de computação científica.

Exploraremos o processo de inversão de matrizes através de várias etapas: leitura de uma matriz quadrada a partir da entrada do usuário, cálculo do determinante e da adjunta da matriz e, finalmente, cálculo da inversa usando esses valores. O laboratório fornecerá experiência prática na implementação dessas operações matemáticas em código C, reforçando sua compreensão tanto dos conceitos de programação quanto dos princípios de álgebra linear.

Ao final deste laboratório, você será capaz de implementar um programa completo de inversão de matrizes e entender as técnicas matemáticas subjacentes envolvidas no processo.

Lendo uma Matriz Quadrada da Entrada do Usuário

Nesta etapa, criaremos um programa para ler uma matriz quadrada da entrada do usuário. Uma matriz quadrada tem um número igual de linhas e colunas, o que é um requisito para calcular a inversa de uma matriz.

Primeiro, vamos entender o que precisamos fazer:

  1. Definir um tamanho máximo para nossa matriz
  2. Obter o tamanho real da matriz do usuário
  3. Ler cada elemento da matriz
  4. Exibir a matriz para verificar nossa entrada

Vamos começar criando um novo arquivo C em nosso diretório de projeto:

  1. Abra o WebIDE e navegue até o diretório do projeto
  2. Crie um novo arquivo chamado matrix_input.c no diretório ~/project

Copie o seguinte código para o arquivo:

#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;
}

Vamos entender os componentes-chave deste código:

  • #define MAX_SIZE 10 - Isso define uma constante para o tamanho máximo da matriz
  • readMatrix() - Uma função que usa loops aninhados para ler cada elemento da matriz
  • displayMatrix() - Uma função que imprime a matriz em formato tabular
  • Na função main(), obtemos o tamanho do usuário e o validamos antes de ler a matriz

Agora, vamos compilar e executar nosso programa:

  1. Abra um terminal no WebIDE

  2. Compile o programa com o seguinte comando:

    cd ~/project
    gcc matrix_input.c -o matrix_input
  3. Execute o programa:

    ./matrix_input

Você deve ver uma saída semelhante a esta:

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

Você criou com sucesso um programa que lê uma matriz quadrada da entrada do usuário e a exibe. Esta é a primeira etapa em nosso processo de cálculo da inversa da matriz.

Calculando o Determinante e o Cofator da Matriz

Antes de podermos calcular a inversa de uma matriz, precisamos entender e implementar duas operações matemáticas chave: encontrar o determinante e o cofator de uma matriz. O determinante é um valor escalar derivado de uma matriz quadrada e desempenha um papel crucial na determinação se uma matriz é invertível.

Nesta etapa, faremos o seguinte:

  1. Aprender o que são determinantes e cofatores
  2. Implementar funções para calculá-los
  3. Testar nossa implementação com uma matriz simples

Vamos criar um novo arquivo para esta etapa:

  1. Crie um novo arquivo chamado matrix_determinant.c no diretório ~/project

Copie o seguinte código para o arquivo:

#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;
}

Vamos entender os componentes-chave deste código:

  • getCofactor() - Esta função extrai uma submatriz removendo uma linha e coluna específicas. Isso é essencial para calcular determinantes e matrizes adjuntas.
  • determinant() - Uma função recursiva que calcula o determinante de uma matriz usando o método de expansão por cofatores.
  • Também verificamos se a matriz é invertível testando se o determinante é diferente de zero.

Entendendo os Conceitos Matemáticos:

  1. Cofator (Cofactor): Para cada elemento em uma matriz, o cofator é o determinante da submatriz formada removendo a linha e a coluna desse elemento, multiplicado por (-1)^(i+j), onde i,j são os índices da linha e da coluna.

  2. Determinante (Determinant): O determinante é um número especial calculado a partir de uma matriz quadrada. Para uma matriz 2×2 [[a,b],[c,d]], o determinante é (a×d - b×c). Para matrizes maiores, usamos a expansão por cofatores.

  3. Invertibilidade (Invertibility): Uma matriz é invertível somente se seu determinante não for zero.

Agora, vamos compilar e executar nosso programa:

  1. Compile o programa com o seguinte comando:

    cd ~/project
    gcc matrix_determinant.c -o matrix_determinant
  2. Execute o programa:

    ./matrix_determinant

Você deve ver uma saída semelhante a esta:

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).

Tente inserir matrizes diferentes, incluindo algumas com determinante zero, para ver como o programa se comporta. Por exemplo, se você inserir uma matriz onde uma linha é um múltiplo de outra linha, o determinante deverá ser zero.

Você implementou com sucesso o cálculo do determinante, que é um componente crítico para encontrar a inversa de uma matriz.

Calculando a Adjunta de uma Matriz

A próxima etapa no cálculo da inversa de uma matriz é calcular a adjunta (também chamada de adjugada) da matriz. A adjunta de uma matriz é a transposta da matriz de cofatores. Uma vez que temos a adjunta e o determinante de uma matriz, podemos calcular a inversa usando a fórmula:

Inversa(A) = Adjunta(A) / Determinante(A)

Nesta etapa, faremos o seguinte:

  1. Implementar a função de cálculo da adjunta
  2. Construir sobre nosso código anterior para preparar a inversão final da matriz

Vamos criar um novo arquivo para esta etapa:

  1. Crie um novo arquivo chamado matrix_adjoint.c no diretório ~/project

Copie o seguinte código para o arquivo:

#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;
}

Vamos entender o novo componente-chave deste código:

  • adjoint() - Esta função calcula a adjunta de uma matriz, que é a transposta da matriz de cofatores. Para cada elemento (i,j) na matriz, nós:
    1. Encontramos a matriz de cofatores removendo a linha i e a coluna j
    2. Calculamos o determinante desta matriz de cofatores
    3. Aplicamos o sinal apropriado ((−1)^(i+j))
    4. Colocamos este valor na posição (j,i) na matriz adjunta (transposta)

Entendendo o Cálculo da Adjunta:

A adjunta (ou adjugada) de uma matriz A é denotada adj(A). Para uma matriz 2×2:

A = [a b]
    [c d]

A adjunta é:

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

Para matrizes maiores, calculamos o cofator de cada elemento e, em seguida, transpomos a matriz resultante.

Agora, vamos compilar e executar nosso programa:

  1. Compile o programa com o seguinte comando:

    cd ~/project
    gcc matrix_adjoint.c -o matrix_adjoint
  2. Execute o programa:

    ./matrix_adjoint

Você deve ver uma saída semelhante a esta:

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

Observe que, neste exemplo, o determinante é 0, o que significa que a matriz não é invertível. Vamos tentar outro exemplo com uma matriz invertível:

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

Neste caso, o determinante é 15 (diferente de zero), o que significa que podemos calcular a inversa desta matriz. Você implementou com sucesso o cálculo da adjunta, que é a penúltima etapa na inversão da matriz.

Calculando a Inversa da Matriz

Agora que implementamos funções para calcular tanto o determinante quanto a adjunta de uma matriz, podemos finalmente calcular a inversa de uma matriz. Como mencionado anteriormente, a fórmula para encontrar a inversa é:

Inversa(A) = Adjunta(A) / Determinante(A)

Nesta etapa final, faremos o seguinte:

  1. Implementar a função de inversão da matriz
  2. Criar um programa completo que lê uma matriz e calcula sua inversa
  3. Adicionar formatação de saída aprimorada para melhor legibilidade

Vamos criar um novo arquivo para esta etapa final:

  1. Crie um novo arquivo chamado matrix_inverse.c no diretório ~/project

Copie o seguinte código para o arquivo:

#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;
}

Vamos entender os novos componentes-chave deste código:

  • inverse() - Esta função calcula a inversa de uma matriz por:

    1. Encontrar o determinante
    2. Verificar se o determinante é diferente de zero (invertível)
    3. Calculando a adjunta
    4. Dividindo cada elemento da adjunta pelo determinante
  • displayFloatMatrix() - Uma nova função para exibir a matriz inversa com precisão de ponto flutuante, uma vez que os elementos inversos não são necessariamente inteiros.

Entendendo a Inversão de Matrizes:

Para uma matriz A, a inversa A^(-1) satisfaz a equação: A × A^(-1) = A^(-1) × A = I, onde I é a matriz identidade.

A fórmula que estamos usando é: A^(-1) = adj(A) / det(A)

Agora, vamos compilar e executar nosso programa:

  1. Compile o programa com o seguinte comando:

    cd ~/project
    gcc matrix_inverse.c -o matrix_inverse
  2. Execute o programa:

    ./matrix_inverse

Você deve ver uma saída semelhante a esta:

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

Vamos verificar o resultado: O produto da matriz original e sua inversa deve ser muito próximo da matriz identidade. Você pode verificar isso manualmente para matrizes pequenas.

Para um exemplo 2×2, vamos tentar:

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

Para uma matriz 2×2, você pode verificar facilmente a inversa usando a fórmula:
Para a matriz A = [[a, b], [c, d]], a inversa é:
A^(-1) = (1/det(A)) × [[d, -b], [-c, a]]

onde det(A) = a×d - b×c

Em nosso exemplo:
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]]

Parabéns! Você implementou com sucesso um calculador completo de inversa de matriz em C.

Resumo

Neste laboratório, implementamos um calculador completo de inversa de matriz em programação C. Ao longo do laboratório, exploramos vários conceitos-chave e os implementamos passo a passo:

  1. Começamos criando um programa para ler uma matriz quadrada da entrada do usuário e exibi-la, aprendendo a lidar com arrays 2D em C.

  2. Em seguida, implementamos o cálculo do determinante usando o método de expansão de cofatores, uma abordagem recursiva que forma a base da inversão de matrizes.

  3. Em seguida, construímos sobre nosso código para calcular a adjunta de uma matriz, que é a transposta da matriz de cofatores.

  4. Finalmente, combinamos todos esses componentes para calcular a inversa de uma matriz usando a fórmula: Inversa = Adjunta / Determinante.

Essas operações matemáticas são fundamentais em álgebra linear e têm amplas aplicações em vários campos, incluindo computação gráfica, aprendizado de máquina, resolução de sistemas de equações lineares e muito mais.

A implementação demonstrou vários conceitos de programação, como:

  • Arrays multidimensionais
  • Funções recursivas
  • Conversão de tipos entre inteiros e números de ponto flutuante
  • Modularidade de funções e organização de código
  • Validação da entrada do usuário

Ao concluir este laboratório, você ganhou experiência prática com a teoria matemática e a implementação de programação de operações de matrizes, particularmente a inversão de matrizes.