Created
October 9, 2015 19:10
-
-
Save will-in-wi/348ae92f2ae8b27aa029 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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