Search code examples
javascriptmathmatrixphysics

Solving non-square system of linear equations in Javascript


I have a system of resistors, something like this: Resistor schematic

I made a website which renders diagrams like this one (not this one exactly). The user can change resistance of each resistor. I want to calculate every current in the system.

I found a solution using Kirchhoff's laws, which gave me a system of linear equations. I solved it with math.js using inverse matrix. This approach worked well on smaller circuits.

In this circuit, i have more equations, than variables, which means that I cannot compute inverse matrix, to solve them. Simplifying them manually, to match the number of unknowns is an option, but that would require a human. The website should be able to calculate everything on its own.

Now I am looking for a way to solve a system of linear equations, which cannot be represented as a square matrix. Any suggestions?

Thanx!

Edit:

My current approach looks like this.

let R1 = 3;
let R2 = 10;
let R3 = 3;
let R4 = 2;
let R5 = 4;
let R6 = 4;
let V1 = 5;

let I1 = 0;
let I2 = 0;
let I3 = 0;
let I4 = 0;
let I5 = 0;
let I6 = 0;

const matrix = [
  [-1, 1, 1, 0, 0, 0],
  [1, -1, 0, 0, 0, -1],
  [0, 0, -1, 1, 1, 0],
  [0, -R2, 0, 0, 0, 0],
  [0, 0, 0, -R6, -R5, 0],
  [0, 0, -R1, -R6, 0, -(R3 + R4)]
];
const result = [0, 0, 0, -V1, 0, -V1];

const inverse = math.inv(matrix);
const currents = math.multiply(inverse, result);

console.log(currents);
[I1, I2, I3, I4, I5, I6] = currents;
<script src="https://cdn.jsdelivr.net/npm/mathjs@9.4.4/lib/browser/math.min.js"></script>

The issue is that in this example, I get wrong solution. I narrowed it down to missing conditions (equations).

I have 6 currents, which means I can have only 6 equations to be able to calculate inverse matrix... But in this case and many others that I have, 6 equations are not enough.

The issue is that I need a computer to make sense out of that. Not a human. So, I need to find a way to solve this kind of problem for 6 variables, but with more than 6 equations.


Solution

  • After a lot of trial and error I found out that the solve function in ml-matrix allows for more than N equations with N variables.

    I also tried the approach with pseudo-inverse, but that also required the matrix to be square.