首頁  >  文章  >  web前端  >  JavaScript 程式檢查冪等矩陣

JavaScript 程式檢查冪等矩陣

PHPz
PHPz轉載
2023-09-01 20:09:161394瀏覽

JavaScript 程序检查幂等矩阵

冪等矩陣是具有相同行數和列數的方陣,當我們將矩陣與其自身相乘時,結果將等於同一個矩陣。我們將得到一個矩陣,我們必須確定它是否是冪等矩陣。

數學上

如果給定矩陣 ix M,則 M 是冪等矩陣,應遵循以下性質 -

M*M = M

矩陣乘法

#一個矩陣與另一個矩陣相乘會產生另一個矩陣,如果給定矩陣是 N*N 的方陣,則所得矩陣也將具有相同的維度 (N*N)。

兩個矩陣A和B相乘的結果矩陣的每個索引(i,j)是矩陣A的第j列與矩陣B的第i列的乘法總和。

輸入

Mat = [ [1, 0],
	    [0, 1]]

輸出

Yes, the given matrix is an Idempotent matrix.

說明

For the cell (0,0): We have to multiply [1,0] with [1,0] => 1* 1 + 0 * 0 = 1. 
For the cell (0,1): We have to multiply [0,1] with [1,0] => 0* 1 + 0 * 1 = 0. 
For the cell (1,0): We have to multiply [1,0] with [0,1] => 1* 0 + 0 * 1 = 0.
For the cell (1,1): We have to multiply [0,1] with [0,1] => 0* 0 + 1 * 1 = 1.  
So, the final matrix we will get is: [ [1, 0], [0, 1]]

方法

我們已經了解了求兩個矩陣相乘的範例和方法,現在讓我們看看實作程式碼以求給定矩陣是否為冪等矩陣的步驟。

  • 首先,我們將建立一個函數,該函數將採用單一參數,該參數將作為要尋找的矩陣,無論它是否是冪等矩陣。

  • 我們將取得矩陣的長度,並使用它通過 for 迴圈遍歷矩陣的每個單元格。

  • 在每個索引或單元格中,我們將使用上述步驟來取得答案矩陣目前單元​​格中存在的值。

  • 我們將使用for迴圈遍歷目前列和行並得到它們的乘法和。

  • 如果目前總和等於目前索引值,則我們將移至下一個值,否則將傳回 false。

  • 根據回傳值,列印目前矩陣是否冪等的語句。

範例

// function to check if the current matrix is an Idempotent matrix or not
function check(mat){

   // getting the size of the given matrix. 
   var n = mat.length;    
   
   // traversing over the given matrix 
   for(var i = 0;i < n; i++){
      for(var j = 0; j<n; j++){
      
         // for the current cell calculating the value present in the resultant matrix 
         
         // variable to store the current cell value 
         var cur = 0;
         for(var k = 0; k<n; k++){
            cur += mat[k][j]*mat[i][k];
         }
         
         // if the current value is not equal to value we got for this cell then return false 
         if(cur != mat[i][j]){
            return false;
         }
      }
   }
   
   // returing true as all the values matched 
   return true;
}

// defining the matrix 
var mat = [[2, -2, -4],
           [-1, 3, 4 ],
           [1, -2, -3]]
console.log("The given matrix is: ")
console.log(mat);

// calling the function to check if the current matrix is idempotent matrix or not 
if(check(mat)){
   console.log("The given matrix is idempotent matrix")
}
else {
   console.log("The given matrix is not idempotent matrix")
}

時間與空間複雜度

上述程式碼的時間複雜度為 O(N^3),其中 N 是給定矩陣的行數。對於每個單元格,我們必須將當前列與當前行相乘以產生因子或 N,總共有 N^N 個單元格。

上述程式碼的空間複雜度為 O(1),因為我們沒有使用任何額外的空間來儲存矩陣。

結論

在本教程中,我們實作了一個 JavaScript 程式來檢查給定矩陣是否是冪等矩陣。冪等矩陣是具有相同行數和列數的方陣,當我們將矩陣與其自身相乘時,結果將等於同一個矩陣。我們以 O(N^3) 時間複雜度實現程式碼,並以 O(1) 空間複雜度工作。

以上是JavaScript 程式檢查冪等矩陣的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除