user3806126 user3806126 - 6 months ago 30
Ruby Question

Ruby: Convert String to Matrix

I have saved a hash with a matrix into a file, like this:

File.open("test.json", "w+") { |file| file.write("#{hash.to_json}") }


The hash contained following data:

{0=>Matrix[[-0.03, 1.3],[0.1,-0.45]],1=>Matrix[[-1.9,1.8,-0.6]]}


Now I read the saved file:

contents = File.read('test.json')
hashAgain = JSON.parse(contents) #Convert it to hash


But if I want to access a Matrix in the hash, the matrix is no longer in the matrix data format:

puts netTrained.values[0].class #=>String


My question is how to convert the "matrix" string back to the matrix data format?

Answer

First, you defined the first matrix wrong. Different number of rows.

Matrix[[-0.03, 1.3, -0.6],[0.1,-0.45]]

gives

ExceptionForMatrix::ErrDimensionMismatch: row size differs (2 should be 3)

Matrix does not accept strings for its creation. But it accepts Arrays. So, one solution would be for you to save the array in the file instead of the Matrix strings. If you save in the file "0.1,-0.45" you can do something like:

Matrix["0.1, -0.45".split(',')]
Comments