一個 C++ 程式來檢查對合矩陣


假設給定一個矩陣 M[r][c],'r' 表示行數,'c' 表示列數,滿足 r = c,形成一個方陣。我們需要檢查給定的方陣是否為對合矩陣

對合矩陣

當矩陣與自身相乘,結果是一個單位矩陣時,該矩陣被稱為對合矩陣。單位矩陣 I 是一個沿主對角線元素均為 1,而其他元素均為 0 的矩陣。因此,我們可以說一個矩陣是對合矩陣當且僅當M*M=I,其中M 是某個矩陣,I 是單位矩陣。

如以下示例所示 −

當我們把矩陣與自身相乘時,結果是單位矩陣;因此給定的矩陣是對合矩陣

Input: { {1, 0, 0},
   {0, -1, 0},
   {0, 0, -1}}
Output: yes
Input: { {3, 0, 0},
   {0, 2, 0},
   {0, 0, 3} }
Output: no

演算法

Start
Step 1 -> define macro as #define size 3
Step 2 -> declare function for matrix multiplication.
   void multiply(int arr[][size], int res[][size])
      Loop For int i = 0 and i < size and i++
         Loop For int j = 0 and j < size and j++
            Set res[i][j] = 0
            Loop For int k = 0 and k < size and k++
               Set res[i][j] += arr[i][k] * arr[k][j]
            End
         End
   End
Step 3 -> declare function to check involutory matrix or not
   bool check(int arr[size][size])
   declare int res[size][size]
   Call multiply(arr, res)
   Loop For int i = 0 and i < size and i++
      Loop For int j = 0 and j < size and j++
         IF (i == j && res[i][j] != 1)
            return false
         End
         If (i != j && res[i][j] != 0)
            return false
         End
      End
   End
   Return true
Step 4 -> In main()
   Declare int arr[size][size] = { { 1, 0, 0 },
      { 0, -1, 0 },
      { 0, 0, -1 } }
   If (check(arr))
      Print its an involutory matrix
   Else
      Print its not an involutory matrix
Stop

#include <bits/stdc++.h>
#define size 3
using namespace std;
// matrix multiplication.
void multiply(int arr[][size], int res[][size]){
   for (int i = 0; i < size; i++){
      for (int j = 0; j < size; j++){
         res[i][j] = 0;
         for (int k = 0; k < size; k++)
            res[i][j] += arr[i][k] * arr[k][j];
      }
   }
}
// check involutory matrix or not.
bool check(int arr[size][size]){
   int res[size][size];
   multiply(arr, res);
   for (int i = 0; i < size; i++){
      for (int j = 0; j < size; j++){
         if (i == j && res[i][j] != 1)
            return false;
         if (i != j && res[i][j] != 0)
            return false;
      }
   }
   return true;
}
int main(){
   int arr[size][size] = { { 1, 0, 0 },
      { 0, -1, 0 },
      { 0, 0, -1 } };
   if (check(arr))
      cout << "its an involutory matrix";
   else
      cout << "its not an involutory matrix";
   return 0;
}

輸出

its an involutory matrix

更新於: 2019 年 9 月 23 日

119 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.