[C++ 언어-기초실습-10] 3X3 행렬의 곱

in #kr-dev7 years ago (edited)

[C++ 언어-기초실습-10] 3X3 행렬의 곱



오늘은 행렬의 곱을 실습을 해보도록 하죠.

1. 3x3 행렬 곱


3x3 행렬의 곱을 하기 위해서는 우선 수학식을 알아야 겠죠.
a1.jpg

위 그림과 같이 결과 행렬의 위치 A에 값을 구하기 위해서는 두 행렬의 곱을 할 때는 앞에 행렬의 행과 뒤의 행렬의 열을 곱해서 행렬 A 위치의 값을 구하게 됩니다. 즉, 행과 열의 곱으로 해서 하나의 행렬 위치의 값을 구한다고 생각하시면 됩니다.

색이 칠해진 위치를 수식으로 하면 아래와 같습니다.

C[0][0] = A[0][0]*B[0][0]+A[0][1]*B[1][0]+A[0][2]*B[2][0];

위 식을 보면 규칙성을 보이실 거에요.

for(int k=0;k<3;k++){
    C[0][0] += A[0][k]*B[k][0];
}

이렇게 A행렬의 행과 B행렬의 열의 위치를 0~2까지 총 3개의 데이터를 곱한 걸 전부 더해서 C[0][0]의 값을 구하게 됩니다.

그리고, 행렬를 표현 할 때는 예전에 설명했지만 다시 설명드리면 무조건 행렬은 for문으로 구현합니다. 2차 행렬은 바로 아래와 같이 2개의 for문으로 구현합니다.

for(int i=0;i<행수;i++){
  for(int j=0;j<열수;ㅓ++){
  }
}

위 코딩이 머리속에서 바로 떠올라야 합니다. 나중에 3차 공간 행렬을 쓸때는 x,y,z식으로 변수를 선언하고 3차 for문으로 해서 위 2차 for문에 한개 for문을 더 추가하면 간단히 표현 할 수 있습니다.

이제 3x3 행렬의 곱을 실제 해봅시다.

2. 코딩


[전체소스]

#include <iostream>

using namespace std;

int main(int argc, char** argv) {
    int A[3][3] = {{1,1,1},
                   {2,2,2},
                   {3,3,3}};                
    int B[3][3] = {{1,2,3},
                   {1,2,3},
                   {1,2,3}};
    int C[3][3] = {0};
    
    //3X3 행렬곱 
    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            for(int k=0;k<3;k++){
                C[i][j]+=A[i][k]*B[k][j];
            }
        }
    }
    
    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            cout<<C[i][j];
            if(j<2) cout<<" ";
        }
        cout<<endl;
    }   
    return 0;
}

[결과]

a2.jpg

마무리


C언어 실습에서 행렬의 대한 부분을 코딩한 것 같은데 갑자기 기억이 잘 안나네요. 중복 post가 된 것이 아닌지 모르겠네요. 아무튼 행렬의 곱을 C++ 상에서 간단히 실습을 해보았네요.


Sponsored ( Powered by dclick )

dclick-imagead

Sort:  

@codingman , lol .. j<열수 i actually never think about the fact that some people actually program in foreign alphabet/charactersets, i don't speak korean i just guess its about matrices or something ... just was on my feed ...

i like the clean cut too

    this.slotbutton[lus] =  this.add.rectangle(this.graphix.x+2+lus*65- (Math.floor((lus-1)/10))*650,this.graphix.y + 65 + (Math.floor((lus-1)/10))*65,64,64, 0x0000aa).setOrigin(0,0).setAlpha(0.5).setInteractive();

gets

50 nice slots in one loop instead of using two intermingling as the y coord depends on the x index

...

guess im a nerd ... sorry if the voting power doesnt mean much these days, for some reason i have seen my main account sit at $500 value for like 2 years now, no matter how much it grows, that's some serious market manipulation math above my braingrade

(and nevermind im just passing by :p)

Thank you for your continued support towards JJM. For each 1000 JJM you are holding, you can get an additional 1% of upvote. 10,000JJM would give you a 11% daily voting from the 700K SP virus707 account.

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.082
BTC 61074.00
ETH 1635.54
USDT 1.00
SBD 0.41