# Solving linear systems in NMatrix

I’m writing some guides for NMatrix, so in the following weeks there should be some posts similar to this one, but more complex.

Linear systems are one of the most useful methods from “common algebra”. Various problems can be represented by them: systems of linear ODEs, operations research optimizations, linear electrical circuits and a lot of the “wording problems” from basic algebra. We can represent these systems as

$Ax = b$

Where $A$ is a matrix of coefficients and $b$ a vector representing the other side of the equation.

I generally prefer to work with examples, so let’s use a very simple 3×3 system from Wikipedia:

$\left( \begin{array}{ccc} 3 & 2 & -1 \\\ 2 & -2 & 4 \\\ -1 & 0.5 & -1\end{array} \right) * x = \left( \begin{array}{c} 1 \\\ -2 \\\ 0\end{array} \right)$

To solve a system like that, it’s necessary to invert $A$ and multiply it by the left of $b$. In order to do this, we first create two NMatrices and that’s where knowing some shortcuts can help: there’s a class called N that can be used to create a new NMatrix by calling its #[] method. Pass the arrays that represent the rows and (optionally) a dtype and that’s it.

The following code does it:

I’m working on more examples of what can be done with simple linear systems and basic Ruby: solving linear circuits and network-flow problems, so this isn’t the last time I’ll post about the subject here. See you next time! :)