Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

행렬 곱셈을 수행하는 C++ 프로그램

<시간/>

행렬은 행과 열의 형태로 배열된 직사각형 숫자 배열입니다.

행렬의 예는 다음과 같습니다.

3*2 행렬은 아래와 같이 3개의 행과 2개의 열로 구성됩니다. -

8 1
4 9
5 6

행렬 곱셈을 수행하는 프로그램은 다음과 같습니다.

예시

#include<iostream>
using namespace std;
int main() {
   int product[10][10], r1=3, c1=3, r2=3, c2=3, i, j, k;
   int a[3][3] = { {2, 4, 1} , {2, 3, 9} , {3, 1, 8} };
   int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 4, 7} };
   if (c1 != r2) {
      cout<<"Column of first matrix should be equal to row of second matrix";
   } else {
      cout<<"The first matrix is:"<<endl;
      for(i=0; i<r1; ++i) {
         for(j=0; j<c1; ++j)
         cout<<a[i][j]<<" ";
         cout<<endl;
      }
      cout<<endl;
      cout<<"The second matrix is:"<<endl;
      for(i=0; i<r2; ++i) {
         for(j=0; j<c2; ++j)
         cout<<b[i][j]<<" ";
         cout<<endl;
      }
      cout<<endl;
      for(i=0; i<r1; ++i)
      for(j=0; j<c2; ++j) {
         product[i][j] = 0;
      }
      for(i=0; i<r1; ++i)
      for(j=0; j<c2; ++j)
      for(k=0; k<c1; ++k) {
         product[i][j]+=a[i][k]*b[k][j];
      }
      cout<<"Product of the two matrices is:"<<endl;
      for(i=0; i<r1; ++i) {
         for(j=0; j<c2; ++j)
         cout<<product[i][j]<<" ";
         cout<<endl;
      }
   }
   return 0;
}

출력

The first matrix is:
2 4 1
2 3 9
3 1 8
The second matrix is:
1 2 3
3 6 1
2 4 7
Product of the two matrices is:
16 32 17
29 58 72
22 44 66

위의 프로그램에서 두 행렬 a와 b는 다음과 같이 초기화됩니다. -

int a[3][3] = { {2, 4, 1} , {2, 3, 9} , {3, 1, 8} };
int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 4, 7} };

첫 번째 행렬의 열 수가 두 번째 행렬의 행 수와 같지 않으면 곱셈을 수행할 수 없습니다. 이 경우 오류 메시지가 인쇄됩니다. 다음과 같이 주어집니다.

if (c1 != r2) {
   cout<<"Column of first matrix should be equal to row of second matrix";
}

행렬과 b는 모두 중첩 for 루프를 사용하여 표시됩니다. 다음 코드 스니펫에서 이를 확인할 수 있습니다.

cout<<"The first matrix is:"<<endl;
for(i=0; i<r1; ++i) {
   for(j=0; j<c1; ++j)
   cout<<a[i][j]<<" ";
   cout<<endl;
}
cout<<endl;
cout<<"The second matrix is:"<<endl;
for(i=0; i<r2; ++i) {
   for(j=0; j<c2; ++j)
   cout<<b[i][j]<<" ";
   cout<<endl;
}
cout<<endl;

그 후, product[][] 행렬은 0으로 초기화됩니다. 그런 다음 중첩 for 루프를 사용하여 2개의 행렬 a와 b의 곱을 찾습니다. 이는 아래 코드 스니펫에 나와 있습니다.

for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j) {
   product[i][j] = 0;
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k) {
   product[i][j]+=a[i][k]*b[k][j];
}

제품을 얻은 후 인쇄됩니다. 이것은 다음과 같이 표시됩니다.

cout<<Product of the two matrices is:"<<endl;
for(i=0; i<r1; ++i) {
   for(j=0; j<c2; ++j)
   cout<<product[i][j]<<" ";
   cout<<endl;
}