# Forum: Ruby Sparse matrix

on 2013-11-17 21:44
Hi,
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

Thanks.

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

value.each{ |k, v|
puts key
puts k
puts v
puts "[#{key}, #{k}] = #{v}"}
}
on 2013-11-17 21:58
On Sun, Nov 17, 2013 at 9:44 PM, aaron v. <lists@ruby-forum.com> 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.

Cheers

robert
on 2013-11-19 18:01
aaron,

You should take a look at NMatrix: https://github.com/sciruby/nmatrix.
It's
a numerical linear algebra library for Ruby built in C++. There is a
sparse
storage type called "yale" which you can use:

require 'nmatrix'

values = [[5,0,3],[4,5,8],[7,8,9]]
matriz1 = NMatrix.new([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
mailing
list. :)

-----
Carlos Agarie
Software Engineer @ Geekie (geekie.com.br)
+55 11 97320-3878
@carlos_agarie

2013/11/17 aaron v. <lists@ruby-forum.com>