Sparse matrix

Emerged me a doubt to perform some operations with dense matrices and
sparse matrices.
I’m doing a few methods to check whether an array is dense or not and
use a hash of hashes, for then do methods of addition and subtraction
between dense and sparse matrices.
Will also have to wear the coerce to do the conversion in the matrix
when performing the operation between the values of arrays.
We have in this code that does the calculation.
An example of sparse arrays in Ruby


matriz1 = ([[5,0,3],[4,5,8],[7,8,9]])
hsh =
while i < 3
while j < 3
if (matriz1[i][j] != 0)
puts matriz1[i][j]
hsh["#{i}"] =
hsh["#{i}"]["#{j}"] = matriz1[i][j]
j += 1
i += 1
hsh.each {|key, value|

value.each{ |k, v|
   puts key
   puts k
    puts v
    puts "[#{key}, #{k}] = #{v}"}


On Sun, Nov 17, 2013 at 9:44 PM, aaron v. [email protected] wrote:

                        puts  matriz1[i][j]
value.each{ |k, v|
   puts key
   puts k
    puts v
    puts "[#{key}, #{k}] = #{v}"}


What was the question again?

Btw. it may actually be more efficient to not use nested Hashes but a
single Hash with Arrays of indexes as keys. Whatever you do, it’s
probably best to abstract away Matrix as a class - even if you
exchange internal representation.




You should take a look at NMatrix:
a numerical linear algebra library for Ruby built in C++. There is a
storage type called “yale” which you can use:

require ‘nmatrix’

values = [[5,0,3],[4,5,8],[7,8,9]]
matriz1 =[3, 3], values, :stype => :yale)

And you should be good to go. If you have any trouble installing or
otherwise using NMatrix, please post on the issue tracker or on the
list. :slight_smile:

Carlos A.
Software Engineer @ Geekie (
+55 11 97320-3878

2013/11/17 aaron v. [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs