How to invert a matrix in JavaScript

亡梦爱人 提交于 2021-02-08 09:55:48

问题


I want to invert matrix a but its not working. I need help.

var a = math.inv([[1,2],[3,4]])
console.log(a)

回答1:


Math does not contain a inv method. Therefore you cannot call it.

You can however define your own matrix inversion method as is done here, or you could use the numeric JavaScript library and call it with:

A = [[1,2,3],
     [4,5,6],
     [7,3,9]];
Ainv = numeric.inv(A);

or use the math.js library and call it with:

math.inv([[1,2],[3,4]])

Notice that you need a surrounding the list of lists with square brackets (here written in boldface).

In that case, a minimal working example would look like:

<html>
<head>
  <script language="JavaScript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.2.1/math.js"></script>
</head>
<body>
  <p id="result">loading result...</p>
  <script>
  var inverted = math.inv([[1,2],[3,4]]);
  document.getElementById("result").textContent = JSON.stringify(inverted);
  </script>
</body>
</html>



回答2:


Your array that represents a matrix should be an array of arrays. Try math.js like this:

var a = math.inv([[1,2],[3,4]])


来源:https://stackoverflow.com/questions/38000569/how-to-invert-a-matrix-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!