C 언어 행렬 곱셈

CBeginner
지금 연습하기

소개

이 랩에서는 C 언어로 행렬 곱셈 프로그램을 작성해 볼 것입니다. 행렬을 생성하고, 행렬 연산을 수행하는 방법을 배우며, 행렬 곱셈의 표준 알고리즘에 대해 논의할 것입니다. 두 행렬을 곱하고 결과 행렬을 출력하는 C 프로그램을 만들 것입니다.

참고: 코딩을 연습하고 gcc 를 사용하여 컴파일하고 실행하는 방법을 배우려면 직접 ~/project/main.c 파일을 생성해야 합니다.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

행렬 생성

먼저, 행렬을 생성하는 방법을 배워보겠습니다. 행렬은 2 차원 배열입니다. 다음은 C 언어에서 2x2 행렬을 선언하고 초기화하는 예시입니다.

int matrix[2][2] = {{1, 2}, {3, 4}};

다음 예시와 같이 두 개의 인덱스를 사용하여 행렬의 특정 요소에 접근할 수 있습니다.

int element = matrix[1][0];

스칼라 값과의 행렬 곱셈

단일 값과의 행렬 곱셈은 간단하며 다음과 같이 수행됩니다.

int arr[2][2], n;
//Enter scalar value
scanf("%d", &n);

//Input matrix elements
for(int i = 0; i < 2; i++) {
    for(int j = 0; j < 2; j++){
        scanf("%d", &arr[i][j]);
    }
}
// Multiply every element of the matrix with the scalar value
for(int i = 0; i < 2; i++) {
    for(int j = 0; j < 2; j++){
        arr[i][j] = arr[i][j] * n;
    }
}

// Print the updated matrix elements
for(int i = 0; i < 2; i++) {
    for(int j = 0; j < 2; j++){
        printf("%d ", arr[i][j]);
    }
    printf("\n");
}

이 프로그램은 사용자가 입력한 스칼라 값으로 행렬의 각 요소를 곱한 다음 업데이트된 행렬을 출력합니다.

두 행렬 간의 행렬 곱셈

두 행렬을 곱하려면 특정 규칙을 따라야 합니다. 첫째, 첫 번째 행렬의 열 수는 두 번째 행렬의 행 수와 같아야 합니다. 둘째, 결과 행렬은 첫 번째 행렬과 동일한 행 수와 두 번째 행렬과 동일한 열 수를 갖습니다.

두 개의 행렬이 있다고 가정해 보겠습니다.

A = {{1, 3, 5},
     {4, 2, 6}};

B = {{7, 4},
     {3, 1},
     {6, 9}};

이 두 행렬을 곱하려면 행과 열에 대해 내적 (dot product) 을 수행합니다. 행렬의 요소는 다음 공식을 사용하여 곱해집니다.

result[row][col] = matrix1[row][0] * matrix2[0][col]
                  + matrix1[row][1] * matrix2[1][col]
                  + matrix1[row][2] * matrix2[2][col]
                  + ...;

다음은 행렬 곱셈에 대한 C 프로그램입니다.

#include <stdio.h>

int main()
{
  int m, n, p, q, c, d, k, sum = 0;

  // define two matrices
  int first[10][10], second[10][10], result[10][10];

  // input the number of rows and columns of the first matrix
  printf("Enter the number of rows and columns of the first matrix:\n");
  scanf("%d %d", &m, &n);

  // input the elements of the first matrix
  printf("Enter the %d elements of the first matrix:\n", m * n);
  for (c = 0; c < m; c++) {
    for (d = 0; d < n; d++) {
      scanf("%d", &first[c][d]);
    }
  }

  // input the number of rows and columns of the second matrix
  printf("Enter the number of rows and columns of the second matrix:\n");
  scanf("%d %d", &p, &q);

  // input the elements of the second matrix
  printf("Enter the %d elements of the second matrix:\n", p * q);
  for (c = 0; c < p; c++) {
    for (d = 0; d < q; d++) {
      scanf("%d", &second[c][d]);
    }
  }

  // check if matrices can be multiplied
  if (n != p) {
    printf("Matrices cannot be multiplied with each other.\n");
  } else {
    // multiplying the matrices
    for (c = 0; c < m; c++) {
      for (d = 0; d < q; d++) {
        for (k = 0; k < p; k++) {
          sum = sum + first[c][k] * second[k][d];
        }
        result[c][d] = sum;
        sum = 0;
      }
    }

    // print the resulting matrix
    printf("The resulting matrix is:\n");
    for (c = 0; c < m; c++) {
      for (d = 0; d < q; d++) {
        printf("%d\t", result[c][d]);
      }
      printf("\n");
    }
  }

  return 0;
}

이 프로그램은 사용자에게 두 행렬의 요소를 입력하도록 요청하고, 곱할 수 있는지 확인하고, 가능하다면 곱하고, 결과 행렬을 출력합니다.

전체 프로그램

다음은 모든 단계를 결합한 전체 프로그램입니다.

#include<stdio.h>

int main()
{
    int n, m, c, d, p, q, k, first[10][10], second[10][10], pro[10][10], sum = 0;

    printf("\nEnter the number of rows and columns of the first matrix: \n\n");
    scanf("%d%d", &m, &n);

    printf("\nEnter the %d elements of the first matrix: \n\n", m*n);
    for(c = 0; c < m; c++) {
        for(d = 0; d < n; d++) {
            scanf("%d", &first[c][d]);
        }
    }

    printf("\nEnter the number of rows and columns of the first matrix: \n\n");
    scanf("%d%d", &p, &q);

    if(n != p)
        printf("Matrices with the given order cannot be multiplied with each other.\n\n");

    else {
        printf("\nEnter the %d elements of the second matrix: \n\n",m*n);

        for(c = 0; c < p; c++) {
            for(d = 0; d < q; d++) {
                scanf("%d", &second[c][d]);
            }
        }

        printf("\n\nThe first matrix is: \n\n");
        for(c = 0; c < m; c++) {
            for(d = 0; d < n; d++) {
                printf("%d\t", first[c][d]);
            }
            printf("\n");
        }

        printf("\n\nThe second matrix is: \n\n");
        for(c = 0; c < p; c++) {
            for(d = 0; d < q; d++){
                printf("%d\t", second[c][d]);
            }
            printf("\n");
        }

        for(c = 0; c < m; c++) {
            for(d = 0; d < q; d++) {
                for(k = 0; k < p; k++) {
                    sum = sum + first[c][k] * second[k][d];
                }
                pro[c][d] = sum;
                sum = 0;
            }
        }

        printf("\n\nThe multiplication of the two entered matrices is: \n\n");
        for(c = 0; c < m; c++) {
            for(d = 0; d < q; d++) {
                printf("%d\t", pro[c][d]);
            }
            printf("\n");
        }
    }
    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

요약

이 랩에서는 C 에서 행렬을 생성하는 방법과 수행할 수 있는 다양한 유형의 행렬 곱셈 연산에 대해 배웠습니다. C 에서 두 행렬의 곱셈을 계산하는 프로그램을 만들었고 행렬 곱셈에 대한 표준 알고리즘에 대해 논의했습니다.