Study with Me!
Seongmo
Study with Me!
전체 방문자
오늘
어제
  • Computer (126)
    • Computer Science (61)
      • Data Structure (51)
      • Algorithm (6)
      • 선형대수 with C++ (4)
    • Arm Architecture (1)
      • Register (0)
      • Assembly Instruction (1)
    • Linux (30)
      • Linux Kernel (4)
      • 라이브러리 함수 구현하기 (0)
      • 쉘, 쉘 명령어 구현하기 (15)
      • Ubuntu (11)
    • AWS (3)
    • Baekjoon (18)
    • Tools (6)
      • Git & Github (5)
      • Vim (1)
    • 개발 환경 (7)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • STL

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Study with Me!

Seongmo

[C/C++] 단위행렬, 영행렬
Computer Science/선형대수 with C++

[C/C++] 단위행렬, 영행렬

2024. 5. 2. 22:15

단위 행렬

: 주대각선 원소가 모두 1이며 나머지 원소는 모두 0인 정사각 행렬

(정사각 행렬은 행과 열의 크기가 같은 행렬)

영 행렬

: 모든 원소가 0인 행렬 (행렬 덧셈의 항등원)


C++로 구현하기

사실 단위행렬은 정사각행렬이어야 하지만 정사각행렬이 아니어도 처리하도록 코드를 짰다.

기존 생성자 함수를 오버로딩해 type이라는 인자를 하나 더 받는 경우를 추가했다.

type 인자 값이 0이면 해당 행렬은 영행렬이고, 1이면 단위행렬이다.

두 함수의 경우 값을 입력할 필요가 없기 때문에 입력을 받지 않고 자동으로 값을 할당한다.

#include <iostream>

#include "matrix.h"

using namespace std;

int main() {
    // 영행렬
    Matrix m1(2, 3, 0);
    // 단위 행렬
    Matrix m2(4, 4, 1);

    m1.print();
    m2.print();

    return 0;
}

Matrix 클래스의 수정 부분

...
class Matrix {
    int **mat;
    int row;
    int col;

public:
    ...
    // 생성자(단위행렬, 영행렬)
    // type이 0이면 영행렬, 1이면 단위행렬
    Matrix(int row, int col, int type) : row(row), col(col) {
        mat = (int **)malloc(sizeof(int *) * row);
        for (int i = 0; i < row; i++)
            mat[i] = (int *)malloc(sizeof(int) * col);

        printf("[ %d X %d %s Matrix ]\n", row, col, (type ? "Identity" : "Zero"));
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (type) {
                    if (i == j) mat[i][j] = 1;
                    else mat[i][j] = 0;
                }
                else {
                    mat[i][j] = 0;
                }
            }
        }
        printf("\n");
    }
    ...
};
...

깃허브 이미지 링크

저작자표시 (새창열림)

'Computer Science > 선형대수 with C++' 카테고리의 다른 글

[C/C++] 행렬의 연산 : 상등  (1) 2024.05.02
[C/C++] 전치 행렬  (0) 2024.05.02
[C/C++] 행렬  (0) 2024.05.02
    'Computer Science/선형대수 with C++' 카테고리의 다른 글
    • [C/C++] 행렬의 연산 : 상등
    • [C/C++] 전치 행렬
    • [C/C++] 행렬
    Study with Me!
    Study with Me!
    Study with Me!

    티스토리툴바