The jblas module provides matrix classes and functions to comfortably work with the matrices.
JBLAS defines the following six classes:
These classes have the usual arithmetic operations defined as well as coercion to make them work as seamlessly as possible with the norm built-in Ruby numerical types.
Technically, jblas-ruby is organized in a number of mixins which are included in the Java objects to add syntactic sugar and make the objects play well with Ruby. Links to these mixins are included in each section.
See also JBLAS::MatrixClassMixin, mat
You create a matrix or vector explicitly by using the DoubleMatrix[], or FloatMatrix[] constructor. For example:
DoubleMatrix[[1,2,3],[4,5,6]] => 1.0 2.0 3.0 4.0 5.0 6.0 DoubleMatrix[1,2,3] => 1.0 2.0 3.0
Since typing DoubleMatrix all the time is a bit cumbersome, jblas also provides the mat function which is a short-hand for DoubleMatrix:
mat[1,2,3] => 1.0 2.0 3.0
Apart from these constructors, there are few more functions which generate matrices or vectors:
hcat and vcat also exist as methods which take an arbitrary number of arguments and returns the horizontal or vertical concatenation of its arguments.
See also JBLAS::MatrixAccessMixin.
To access individual elements, use the [] or []= methods, or get, and put respectively.
Rows and columns can be accessed with get_row, put_row and get_column, put_column.
You can also often use ranges or enumerables with [] and []=, for example
x[0..2, [1,2,3]]
See also JBLAS::MatrixAccessMixin.
Arithmetic is defined using the usual operators, that is
Multiplication is the usual (linear algebra) multiplication.
There exist also non-operator versions (which are the original Java functions) These also give you more control over the generation of temporary objects. The suffix "!" or "i" indicates that the computation is performed in-place on the left operand.
Some special functions exist for adding the same column vector to all columns of a matrix, or row vector to all rows:
See also JBLAS::MatrixEnumMixin.
Both the matrices and vectors implement the Enumerable mixin. Matrices behave as if they are a linear array of their elements (going down rows first). If you want to iterate over rows or columns, use the rows_to_a or columns_to_a methods, as well as each_row and each_column.
JBLAS defines a large number of mathematical functions. You can either call these as a method on a matrix, vector, or even number, or in the usual notation as a function.
By adding the suffix "i" or "!" to the method functions, you again perform the computation in-place. For example
exp(x)
returns a copy of x, but
exp(x) exp!(x)
do not.
Some functions to deal with geometric properties:
In order to solve the linear equation a * x = b, with b either being a matrix or a vector, call solve:
x = a.solve(b)
or
solve(a, b)
Compute the eigenvalue of a square matrix a with
e = eig(a)
Compute the eigenvectors as well with
u, d = eigv(a)
eigv returns two matrices, the matrix u whose columns are the eigenvectors, and the matrix d, whose diagonal contains the eigenvalues.
Compute the singular value decomposition of an (arbitrarily shaped) matrix a with
u, s, v = svd(a)
The columns of u and v will contain the singular vectors, and s is a vector containing the singular values.
You can also compute a sparse SVD with svd(a, true) (meaning that u and v are not square but have the minimal rectangular size necessary).
Finally, svdv(a) computes only the singular values of a.
MatrixFactory | = | { :double => DoubleMatrix, :float => FloatMatrix | Module Functions | |
FUNCTIONS | = | { 'abs' => 'Compute the absolute value.', 'acos' => 'Compute the arcus cosine.', 'asin' => 'Compute the arcus sine.', 'atan' => 'Compute the arcus tangens.', 'cbrt' => 'Compute the cube root.', 'ceil' => 'Round up to the next integer', 'cos' => 'Compute the cosine.', 'cosh' => 'Compute the hyperbolic cosine.', 'exp' => 'Compute the exponential function.', 'floor' => 'Round down to the next integer', 'log' => 'Compute the natural logarithm', 'log10' => 'Compute the base-10 logarithm', 'signum' => 'Compute the sign', 'sin' => 'Compute the sine', 'sinh' => 'Compute the hyperbolic sine', 'sqrt' => 'Compute the square root', 'tan' => 'Compute the tangens', 'tanh' => 'Compute the hyperbolic tangens' | ||
PI | = | Math::PI | ||
I | = | ComplexDouble::I |
Check whether matrix is square. Raises Errors::MatrixNotSquare if it isn‘t.
# File lib/jblas/functions.rb, line 47 def check_matrix_square(m) unless m.square? raise Errors::MatrixNotSquare end end
Compute the Cholesky decomposition of a square, positive definite matrix.
Returns a matrix an upper triangular matrix u such that u * u.t is the original matrix.
# File lib/jblas/functions.rb, line 346 def cholesky(x) check_matrix_square(x) begin Decompose.cholesky(x) rescue org.jblas.exceptions.LapackPositivityException raise Errors::MatrixNotPositiveDefinite end end
Compute the determinant of a square matrix.
Internally computes the LU factorization and then takes the product of the diagonal elements.
# File lib/jblas/functions.rb, line 359 def det(x) check_matrix_square(x) l, u, p = lup(x) return u.diag.prod end
Return the diagonal of a matrix or return a matrix whose diagonal is specified by the vector
# File lib/jblas/functions.rb, line 101 def diag(x) if x.vector? mat.diag(x) else x.diag end end
Computing the eigenvalues of matrix.
# File lib/jblas/functions.rb, line 203 def eig(x) check_matrix_square(x) if x.symmetric? return Eigen.symmetric_eigenvalues(x) else return Eigen.eigenvalues(x) end end
Computing the eigenvectors of matrix.
u, v = eigv(x)
u are the eigenvalues and v is a diagonal matrix containing the eigenvalues
# File lib/jblas/functions.rb, line 218 def eigv(x) check_matrix_square(x) if x.symmetric? return Eigen.symmetric_eigenvectors(x).to_a else return Eigen.eigenvectors(x).to_a end end
Return the identity matrix of given size.
# File lib/jblas/functions.rb, line 110 def eye(n) mat.eye(n) end
Returns the horizontal concatenation of all arguments.
See also MatrixGeneralMixin#hcat.
# File lib/jblas/functions.rb, line 247 def hcat(*args) args.map {|s| s.to_matrix}.inject{|s,x| s = s.hcat x} end
Convenience function for converting arbitrary objects into indices.
# File lib/jblas/mixin_access.rb, line 152 def idx(i) i.to_indices end
Generate an array of n linearly spaced points starting at a, ending at b.
# File lib/jblas/functions.rb, line 271 def linspace(a, b, n) (0...n).map do |i| t = Float(i) / (n-1) (1-t)*a + t*b end end
Generate an array of n logarithmically spaced points starting at 10^a and ending at 10^b.
# File lib/jblas/functions.rb, line 280 def logspace(a, b, n) (0...n).map do |i| t = Float(i) / (n-1) 10**( (1-t)*a + t*b ) end end
Compute the LU factorization with pivoting.
Returns matrices l, u, p
# File lib/jblas/functions.rb, line 335 def lup(x) check_matrix_square(x) result = Decompose.lu(x) return result.l, result.u, result.p end
Construct a matrix. Use it like this:
mat[1,2,3] -> constructs a column vector mat[[1,2,3],[4,5,6]] -> construct a rectangular matrix
# File lib/jblas/functions.rb, line 69 def mat(type=:double) MatrixFactory[type] end
Return the largest element of a vector.
# File lib/jblas/functions.rb, line 318 def max(x) x.max end
Return the smallest element of a vector.
# File lib/jblas/functions.rb, line 313 def min(x) x.min end
Compute power, in-place.
# File lib/jblas/functions.rb, line 188 def powi(x, y) MatrixFunctions.powi(x, y) end
Construct a matrix or vector with elements randomly drawn uniformly from [0, 1].
If the second argument is omitted, a column vector is constructed.
# File lib/jblas/functions.rb, line 118 def rand(n=1,m=nil) if m mat.rand(n,m) else mat.rand(n) end end
Construct a matrix or vector with elements randomly drawn from a Gaussian distribution with mean 0 and variance 1. With one argument, construct a vector, with two a matrix.
If the second argument is omitted, a column vector is constructed.
# File lib/jblas/functions.rb, line 131 def randn(n=1,m=nil) if m mat.randn(n,m) else mat.randn(n) end end
Replicate a matrix a certain number of horizontal and vertical times.
For example:
repmat(mat[[1,2,3],[4,5,6]], 1, 2) => [1.0, 2.0, 3.0, 1.0, 2.0, 3.0; 4.0, 5.0, 6.0, 4.0, 5.0, 6.0]
# File lib/jblas/functions.rb, line 265 def repmat(m, r, c) m.to_matrix.repmat(r, c) end
Solve the linear equation a*x = b. See also MatrixMixin#solve.
# File lib/jblas/functions.rb, line 228 def solve(a, b) a.solve b end
Compute the singular value decompositon of a rectangular matrix.
Returns matrices u, s, v such that u*diag(s)*v.t is the original matrix. Put differently, the columns of u are the left singular vectors, the columns of v are the right singular vectors, and s are the singular values.
# File lib/jblas/functions.rb, line 372 def svd(x, sparse=false) if sparse usv = Singular.sparseSVD(x) else usv = Singular.fullSVD(x) end return usv.to_a end
Compute the singular values of a rectangular matrix.
# File lib/jblas/functions.rb, line 382 def svdv(x) Singular.SVDValues(x) end
Times a block and returns the elapsed time in seconds.
For example:
tictoc { n = 100; x = randn(n, n); u, d = eigv(x) }
Times how long it takes to generate a random 100*100 matrix and compute its eigendecomposition.
# File lib/jblas/functions.rb, line 400 def tictoc saved_time = Time.now yield return Time.now - saved_time end
Returns the vertical concatenation of all arguments
See also MatrixGeneralMixin#vcat.
# File lib/jblas/functions.rb, line 254 def vcat(*args) args.map {|s| s.to_matrix}.inject{|s,x| s = s.vcat x} end