solve the system ax = b for different b’s in javascript

Assuming a is an n by n matrix and b is a n by k matrix. We can solve the system ax=b using the LUDecomposition method provided by the math.js library.

Here's an example code snippet:

index.tsx
const math = require('mathjs');

const a = math.matrix([
  [2, -1, 0],
  [-1, 2, -1],
  [0, -1, 2],
]);

const b = math.matrix([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
]);

const lu = math.lusolve(a, b);

console.log(lu);
222 chars
18 lines

In this example, a is a 3 by 3 matrix and b is a 3 by 3 matrix (for simplicity).

The lusolve method returns the solution as a n by k matrix. The resulting lu matrix would contain the solutions:

index.tsx
[
  [ 3, 0, 3 ],
  [ 6, 6, 6 ],
  [ 9, 12, 9 ]
]
49 chars
6 lines

where each column represents the solution to ax=b for each b in the original matrix.

related categories

gistlibby LogSnag