Home > Web Front-end > JS Tutorial > body text

JS implements simple two-dimensional matrix product operation_javascript skills

WBOY
Release: 2016-05-16 15:17:59
Original
2516 people have browsed it

The example in this article describes how to implement a simple two-dimensional matrix product operation using JS. Share it with everyone for your reference, the details are as follows:

The screenshot of the Console console is as follows:

(The above picture shows the output result directly put into the code (the premise that matrix A can be multiplied by matrix B is that the number of columns of matrix A is equal to the number of rows of matrix B)

<!DOCTYPE html>
<html>
  <head>
    <title>demo</title>
  </head>
  <body>
  </body>
  <script type="text/javascript">
    function log(msg) {
      console.log(msg);
    }
    /**
    * 可视化的打印出矩阵的数据
    */
    function printMatrixData(data) {
      console.log(data);
      if(!data) {
        return;
      }
      var numberSize = 5;
      for(var i=0, len=data.length; i<len; i++) {
        var row = data[i];
        var rowLog = "(";
        for(var j=0, jLen=row.length; j<jLen; j++) {
          rowLog += row[j];
          // 补齐空格
          rowLog += indent(numberSize - (row[j]+"").length);
        }
        rowLog+=")";
        console.log(rowLog);
      }
    }
    /**
    * 拼接指定长度的空格
    */
    function indent(length) {
      var empty = "";
      for(var i=0; i<length; i++) {
        empty += " ";
      }
      return empty;
    }
    /**
    * 矩阵原型
    */
    function Matrix(data) {
      // 这里必须传一个二维数组,最好严格检验一下
      if(typeof data !== "object" || typeof data.length === "undefined" || !data) {
        throw new Error("data's type is error");
      }
      this.data = data;
      this.cols = data.length;
    }
    var M = {
      findByLocation: function(data, xIndex, yIndex) {
        if(data && data[xIndex]) {
          return data[xIndex][yIndex];
        }
      },
      // 矩阵乘积
      multiply: function(m, n) {
        if(!m instanceof Matrix && !n instanceof Matrix) {
          throw new Error("data's type is error");
        }
        var mData = m.data;
        var nData = n.data;
        if(mData.length == 0 || nData.length == 0) {
          return 0;
        }
        if(mData[0].length != nData.length) {
          throw new Error("the two martrix data is not allowed to dot");
        }
        var result = [];
        for(var i=0, len=mData.length; i<len; i++) {
          var mRow = mData[i];
          result[i] = [];
          for(var j=0, jLen=mRow.length; j<jLen; j++) {
            var resultRowCol = 0;
            // 如果n矩阵没有足够的列数相乘,转入m矩阵下一行
            if(typeof this.findByLocation(nData, 0, j) === "undefined") {
              break;
            }
            for(var k=0, kLen=jLen; k<kLen; k++) {
              resultRowCol += mRow[k]*this.findByLocation(nData, k, j);
            }
            result[i][j] = resultRowCol;
          }
        }
        return result;
      }
    };
    var m = new Matrix([[2, -1], [-2, 1], [-1, 2]]);
    var n = new Matrix([[4, -3], [3, 5]]);
    var result = M.multiply(m, n);
    printMatrixData(result);
    var m2 = new Matrix([[2, 3, 1], [5, 2, 4], [-3, 2, 0]]);
    var n2 = new Matrix([[11], [5], [8]]);
    var result2 = M.multiply(m2, n2);
    printMatrixData(result2);
  </script>
</html>
Copy after login

Readers who are interested in more content related to JavaScript operations can check out the special topic on this site: "Summary of JavaScript mathematical operations usage"

I hope this article will be helpful to everyone in JavaScript programming.

Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!