views:

77

answers:

1

As far as I understood, matrices are very inflexible to work with. Therefor, I'm trying to get an array of vectors do deal with. My needs are: to be able to add vectors and make arithmetical operations on their components. Writing the code below,

require 'matrix'

x = Matrix.rows( IO.readlines("input.txt").each {|line| line.split} )

puts x.row_vectors

ruby falls into an exception. Why?

matrix.rb:1265:in `to_s': undefined method `join' for "1.2357 2.1742 -5.4834 -2.0735":String (NoMethodError)

OK then, I've calmed down and tried another approach. I wrote:

a = Array.[]( IO.readlines("input.txt").each {|line| Vector.[](line.split) } )

But the only way I can access my vectors inside an array is adressing the second index:

puts a[0][0]

This means, that when I would like to access desired scalar inside a vector, I'll will be forced to use the third index, like:

puts a[0][0][1]

So, the second question is - where the hell that second index comes from? How to get rid of it? Am I missing something when reading data into array?

+1  A: 

I can't reproduce your first problem. Extracting what looks like input.txt, I can execute that first expression without an exception.

As to the second question, your expression seems kind of complex. How about:

b = IO.readlines("input.txt").map { |x| x.split(' ') }

This will get you a "2D" array of arrays, and you will need only two subscripts. (As to your question about where did the extra array come from, you got one from the Array constructor, one from IO.readlines, and one from the Vector constructor . . . I think.)

Or maybe:

result = []
IO.foreach('input.txt') { |ln| result << ln.split(' ') }
DigitalRoss
You're right. Anyway, now I got another similar issue http://stackoverflow.com/questions/1480996/accessing-aan-array-of-vectors-trouble
gmile