কম্পিউটার টিউটোরিয়াল

ম্যাট্রিক্স গুণন অ্যালগরিদম


এই বিভাগে আমরা দেখব কিভাবে দুটি ম্যাট্রিক্স গুণ করা যায়। ম্যাট্রিক্স গুণন শুধুমাত্র সঞ্চালিত হতে পারে, যদি এটি এই শর্তটি সন্তুষ্ট করে। ধরুন দুটি ম্যাট্রিক্স হল A এবং B, এবং তাদের মাত্রা হল A (m x n) এবং B (p x q) ফলাফল ম্যাট্রিক্স পাওয়া যাবে যদি এবং শুধুমাত্র যদি n =p হয়। তাহলে ফলাফলের ম্যাট্রিক্স C এর ক্রম হবে (m x q)।

অ্যালগরিদম

matrixMultiply(A, B):
Assume dimension of A is (m x n), dimension of B is (p x q)
Begin
   if n is not same as p, then exit
   otherwise define C matrix as (m x q)
   for i in range 0 to m - 1, do
      for j in range 0 to q – 1, do
         for k in range 0 to p, do
            C[i, j] = C[i, j] + (A[i, k] * A[k, j])
         done
      done
   done
End

উদাহরণ

#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

  1. ফোর্ড ফুলকারসন অ্যালগরিদম

  2. ফ্লয়েড ওয়ারশাল অ্যালগরিদম

  3. C++ এ স্ট্রসেনের ম্যাট্রিক্স সমীকরণ মনে রাখার সহজ উপায়

  4. পাইথন প্রোগ্রাম দুটি ম্যাট্রিক্সের গুণন।