Skip to content

Instantly share code, notes, and snippets.

@will-in-wi
Created October 9, 2015 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save will-in-wi/348ae92f2ae8b27aa029 to your computer and use it in GitHub Desktop.
Save will-in-wi/348ae92f2ae8b27aa029 to your computer and use it in GitHub Desktop.
require 'pry'
# A linear algebra matrix row.
class Row
def initialize(arr)
@arr = arr.map(&:to_r)
end
def map_with_index
arr = @arr.map.with_index do |val, i|
yield(val, i)
end
Row.new(arr)
end
def +(other)
map_with_index do |val, i|
val + other[i]
end
end
def -(other)
map_with_index do |val, i|
val - other[i]
end
end
def *(other)
Row.new(@arr.map { |val| (val * other).to_r })
end
def [](i)
@arr[i]
end
def to_s
arr = @arr.map do |val|
if val.denominator == 1
val.to_i
else
val
end
end
"[ #{arr.join(' ')} ]"
end
end
matrix = [
Row.new([-Rational(5, 6), Rational(1, 3), Rational(11, 6), 1, 0, 0]),
Row.new([0, Rational(2, 3), 2, 0, 1, 0]),
Row.new([1, -Rational(1, 2), -Rational(5, 2), 0, 0, 1])
]
matrix[0] = matrix[0] * -Rational(6, 5)
matrix[1] = matrix[1] * Rational(3, 2)
matrix[2] = matrix[2] - matrix[0]
matrix[2] = matrix[2] * -10
matrix[2] = matrix[2] - matrix[1]
# matrix[0] = matrix[0] - (matrix[1] * Rational(3, 2))
puts matrix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment