Brr. Jon put on a hoody, turned around. I told him to STAND STILL. Knocked a huge spider off his back with box of dryer sheets, squished it.
Ruby Matrix and Vector additions
Working with matrices and vectors in Ruby before has been annoying because methods I expected to find were not there, and there wasn't much documentation. Here, I present some simple additions to the Matrix and Vector classes that I found helpful.
Ruby
class Matrix
# Assign the given value to the slot at the specified row and column
def []=(row, column, value)
@rows[row][column] = value
end
# Create an n by n matrix where each slot is initialized to the given value
def Matrix.square(n, value)
matrix = Matrix.zero(n)
(0...n).each do |row|
(0...n).each do |col|
matrix[row, col] = value
end
end
matrix
end
# Create an m by n matrix where each slot is initialized to the given value
def Matrix.fill(m, n, value)
rows = []
m.times do
row = []
n.times { row << value }
rows << row
end
Matrix.rows(rows)
end
# Returns a pretty string representation of the matrix
def to_s
[sprintf("%d x %d Matrix", @rows.length, column_size),
@rows.map { |row| row.inspect }].flatten.join("\n")
end
end
class Vector
# Iterate over all elements in the vector
def each
raise ArgumentError unless block_given?
@elements.each { |element| yield element }
end
# Returns true if the vector includes the given item
def include?(other)
to_a.include? other
end
end
Here are some examples of how to use the new methods:
Ruby
=> Matrix[["a", "a", "a"], ["a", "a", "a"], ["a", "a", "a"]]
irb(main):040:0> puts matrix
3 x 3 Matrix
["a", "a", "a"]
["a", "a", "a"]
["a", "a", "a"]
=> nil
irb(main):041:0> other_matrix = Matrix.fill(2, 3, 'b')
=> Matrix[["b", "b", "b"], ["b", "b", "b"]]
irb(main):042:0> other_matrix[1, 2] = 'new value'
=> "new value"
irb(main):043:0> puts other_matrix
2 x 3 Matrix
["b", "b", "b"]
["b", "b", "new value"]
=> nil
irb(main):055:0> other_matrix.row_vectors.each { |row| row.each { |el| puts el } }
b
b
b
b
b
new value
=> [Vector["b", "b", "b"], Vector["b", "b", "new value"]]
irb(main):056:0> num_matrix = Matrix.square(3, 0)
=> Matrix[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
irb(main):057:0> num_matrix[0, 1] = 1
=> 1
irb(main):058:0> num_matrix[0, 2] = 2
=> 2
irb(main):059:0> num_matrix[1, 0] = 3
=> 3
irb(main):060:0> num_matrix[1, 1] = 4
=> 4
irb(main):061:0> puts num_matrix
3 x 3 Matrix
[0, 1, 2]
[3, 4, 0]
[0, 0, 0]
=> nil
irb(main):062:0> num_matrix.row_vectors.select { |row| row.include? 4 }
=> [Vector[3, 4, 0]]
Love the top answer here: htt…
Love the top answer here: http://stackoverflow.com/questions/3974734
Me = backseat SCII player. Gla…
Me = backseat SCII player. Glance up from studying DB, see Jon’s marines being eaten by zerglings, shout “Run, you fool!”, resume reading.
Yay, databases project done an…
Yay, databases project done and submitted.