diff --git a/lib/matrix.rb b/lib/matrix.rb index 026492b..30f9f81 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -878,57 +878,36 @@ class Matrix end # - # Matrix addition. + # Matrix addition and subtraction. # Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]] # => 6 0 # -4 12 # - def +(m) - case m - when Numeric - Matrix.Raise ErrOperationNotDefined, "+", self.class, m.class - when Vector - m = self.class.column_vector(m) - when Matrix - else - return apply_through_coercion(m, __method__) - end - - Matrix.Raise ErrDimensionMismatch unless row_count == m.row_count and column_count == m.column_count - - rows = Array.new(row_count) {|i| - Array.new(column_count) {|j| - self[i, j] + m[i, j] - } - } - new_matrix rows, column_count - end - - # - # Matrix subtraction. # Matrix[[1,5], [4,2]] - Matrix[[9,3], [-4,1]] # => -8 2 # 8 1 # - def -(m) - case m - when Numeric - Matrix.Raise ErrOperationNotDefined, "-", self.class, m.class - when Vector - m = self.class.column_vector(m) - when Matrix - else - return apply_through_coercion(m, __method__) - end + %i(+ -).each do |op| + define_method(op) do |m| + case m + when Numeric + Matrix.Raise ErrOperationNotDefined, op, self.class, m.class + when Vector + m = self.class.column_vector(m) + when Matrix + else + return apply_through_coercion(m, op) + end - Matrix.Raise ErrDimensionMismatch unless row_count == m.row_count and column_count == m.column_count + Matrix.Raise ErrDimensionMismatch unless row_count == m.row_count && column_count == m.column_count - rows = Array.new(row_count) {|i| - Array.new(column_count) {|j| - self[i, j] - m[i, j] + rows = Array.new(row_count) {|i| + Array.new(column_count) {|j| + self[i, j].send(op, m[i, j]) + } } - } - new_matrix rows, column_count + new_matrix rows, column_count + end end #