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
Where is a matrix of coefficients and 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:
To solve a system like that, it’s necessary to invert and multiply it by the left of . 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:
A = N[[3, 2, -1], [2, -2, 4], [-1, 0.5, -1], :dtype => :float64]
b = N[[1, -2, 0], :dtype => :float64].transpose
A.shape # => [3, 3]
b.shape # => [3, 1]
# x = A^(-1) * b
x = A.inverse.dot b
x.shape # => [3, 1]
x # => [[1.0], [-2.0], [-2.0]]
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! :)