Project

General

Profile

Feature #10059 » using_define_method_for_Matrix__arithmetic.patch

gogotanaka (Kazuki Tanaka), 07/18/2014 08:29 AM

View differences:

lib/matrix.rb
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
#
(3-3/3)