JavaScript 检查幂等矩阵

JavaScript 检查幂等矩阵

幂等矩阵是一个具有相同行数和列数的方阵,当我们将矩阵乘以自身时,结果等于相同的矩阵。我们将获得一个矩阵,然后判断它是否是幂等矩阵。

数学上

如果给定的矩阵为M,则M是幂等矩阵的条件为−

M*M = M

矩阵的乘法

矩阵与另一个矩阵相乘会得到另一个矩阵,如果给定的矩阵是NN的方阵,则结果矩阵的维数也是相同的(NN)。

矩阵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)的空间复杂度下工作。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程