JavaScript 程序检查幂等矩阵

PHPz
PHPz 转载
2023-09-01 20:09:16 1060浏览

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,如有侵犯,请联系admin@php.cn删除