Forum: Ruby Sparse matrix

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
381fbcafb14d46996d7a0804147480a2?d=identicon&s=25 aaron v. (aaron_v)
on 2013-11-17 21:44
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}"}
13d0171c6ee97074d61f182a6e3a9f4e?d=identicon&s=25 Robert K. (robert_k78)
on 2013-11-17 21:58
(Received via mailing list)
On Sun, Nov 17, 2013 at 9:44 PM, aaron v. <> 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.


Carlos Agarie (Guest)
on 2013-11-19 18:01
(Received via mailing list)

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. :)

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

2013/11/17 aaron v. <>
This topic is locked and can not be replied to.