3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptで行列の掛け算をするサンプルプログラム

Posted at

JavaScriptで2次元配列を行列として掛け算するプログラムのサンプルです。

dot.js
function dot(matrix1, matrix2){
  var res = [];
  var row1 = matrix1.length;
  var row2 = matrix2.length;
  var col1 = matrix1[0].length;
  var col2 = matrix2[0].length;

  for(var i1 = 0; i1 < row1; i1++){
    res.push([]);
    for(var i2 = 0; i2 < col2; i2++){
      res[i1].push(0);
      for(var i3 = 0; i3 < col1; i3++){
        res[i1][i2] += matrix1[i1][i3] * matrix2[i3][i2];
      }
    }
  }

  return res;
}
matrix1 =
\begin{pmatrix}
1 & 2
\end{pmatrix}
matrix2 =
\begin{pmatrix}
1 \\
2
\end{pmatrix}

を掛ける場合、以下のように関数を使用します。

calc.js
var matrix1 = [[1, 2]]; //1行2列
var matrix2 = [[1], [2]]; //2行1列

dot(matrix1, matrix2);
> [[5]]
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?