Statistics and matrix algebra in Ruby
-
13-09-2019 - |
Question
I need to inverse a variance-covariance matrix in Ruby and vector by matrix multiplication. Which numerical Ruby library/Gem should I use?
Solution
Try using the 'matrix' library:
http://www.ruby-doc.org/stdlib/libdoc/matrix/rdoc/index.html
OTHER TIPS
A numerically more stable possibility than direct inversion is to use a Cholesky decomposition with the package you find here:
require 'Cholesky.rb'
require 'pp'
# m is the covariance matrix you want to invert (it is positive semidefinite)
l = m.cholesky
li = l.inverse
lit = li.transpose
# lit*li is approximately the inverse and the next line shows this
pp lit*li*m
Better than inverting l is to use the method described in the wikpedia article linked above.
If your problem is numerically too unstable then consider the Singular Value Decomposition, but I don't have code for it.
If you can compile code, use ruby-gsl
gem install gsl
The inverse can be obtained using LU module
inverse=GSL::Linalg::LU.invert(matrix)
There is NMatrix. There is support for various operations, including some from BLAS and LAPACK (by using ATLAS).