diff --git a/lib/matrix.rb b/lib/matrix.rb index 17900dd..b3ad3c2 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -1867,14 +1867,13 @@ class Vector end # - # Returns the cross product of this vector with the other. + # Returns the cross product of this vector with the others. # Vector[1, 0, 0].cross_product Vector[0, 1, 0] => Vector[0, 0, 1] # - def cross_product(v) - Vector.Raise ErrDimensionMismatch unless size == v.size && v.size == 3 - Vector[ v[2]*@elements[1] - v[1]*@elements[2], - v[0]*@elements[2] - v[2]*@elements[0], - v[1]*@elements[0] - v[0]*@elements[1] ] + def cross_product(*vs) + Vector.Raise ErrDimensionMismatch unless vs.all?{ |v| v.size == size } && size == vs.count + 2 + rows = Array.new(size) {|i| Vector.basis(size, i) }, self, *vs + Matrix.rows(rows).laplace_expansion(0, :row) end # diff --git a/test/matrix/test_vector.rb b/test/matrix/test_vector.rb index 820bce5..2c687cd 100644 --- a/test/matrix/test_vector.rb +++ b/test/matrix/test_vector.rb @@ -132,8 +132,14 @@ class TestVector < Test::Unit::TestCase end def test_cross_product - v = Vector[1, 0, 0].cross_product Vector[0, 1, 0] - assert_equal(Vector[0, 0, 1], v) + v2 = Vector[1, 2].cross_product + assert_equal(Vector[2, -1], v2) + v3 = Vector[1, 0, 0].cross_product Vector[0, 1, 0] + assert_equal(Vector[0, 0, 1], v3) + v4 = Vector[3, 5, 2, 1].cross_product(Vector[4, 3, 1, 8], Vector[2, 9, 4, 3]) + assert_equal(Vector[-16, 65, -139, 1], v4) + assert_raise(Vector::ErrDimensionMismatch) { Vector[1, 2].cross_product(Vector[1, 4, 9]) } + assert_raise(Vector::ErrDimensionMismatch) { Vector[1, 2].cross_product(Vector[2, -1]) } end def test_r