행렬 전치 프로그램

C++Beginner
지금 연습하기

소개

이 랩에서는 C++ 에서 행렬의 전치 (transpose) 를 수행하는 과정을 안내합니다. 행렬의 전치는 행렬의 행과 열을 서로 바꾸어 얻으며, 열이 행이 되고 행이 열이 되는 새로운 행렬을 생성합니다.

행렬 초기화

  1. mat1mat2 두 개의 3x3 행렬을 선언합니다.
  2. coutcin을 사용하여 사용자에게 행렬의 요소를 입력하도록 요청합니다.
  3. cout을 사용하여 원래 행렬 mat1을 표시합니다.
#include <iostream>

using namespace std;

int main()
{
    // Initializing matrices
    int mat1[3][3], mat2[3][3];
    int i, j;

    // Getting elements input by user
    cout << "Enter the elements of Matrix (3x3): " << endl;
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            cin >> mat1[i][j];
        }
    }

    // Displaying the original matrix
    cout << "\nMatrix is: " << endl;
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            cout << mat1[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

행렬 전치

  1. 원래 행렬의 행과 열을 바꿔서 행렬의 전치를 수행합니다.
  2. 전치된 행렬의 결과를 mat2에 저장합니다.
#include <iostream>

using namespace std;

int main()
{
    // Initializing matrices
    int mat1[3][3], mat2[3][3];
    int i, j;

    // Getting elements input by user
    cout << "Enter the elements of Matrix (3x3): " << endl;
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            cin >> mat1[i][j];
        }
    }

    // Displaying the original matrix
    cout << "\nMatrix is: " << endl;
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            cout << mat1[i][j] << " ";
        }
        cout << endl;
    }

    // Transposing Matrices
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            mat2[i][j] = mat1[j][i];
        }
    }

    // Displaying the transposed matrix
    cout << "\nTransposed matrix is: " << endl;
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            cout << mat2[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

전체 코드

#include <iostream>

using namespace std;

int main()
{
    // Initializing matrices
    int mat1[3][3], mat2[3][3];
    int i, j;

    // Getting elements input by user
    cout << "Enter the elements of Matrix (3x3): " << endl;
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            cin >> mat1[i][j];
        }
    }

    // Displaying the original matrix
    cout << "\nMatrix is: " << endl;
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            cout << mat1[i][j] << " ";
        }
        cout << endl;
    }

    // Transposing Matrices
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            mat2[i][j] = mat1[j][i];
        }
    }

    // Displaying the transposed matrix
    cout << "\nTransposed matrix is: " << endl;
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            cout << mat2[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

요약

이 랩에서는 C++ 에서 행렬의 전치를 수행하는 과정을 안내했습니다. 주어진 단계를 따르면 행렬을 초기화하고 전치하는 방법에 대한 이해도가 높아졌을 것입니다. 행렬의 전치는 선형 대수학에서 중요한 연산이며, C++ 에서 이를 수행하면 다양한 계산 작업에 도움이 될 수 있습니다.