diff options
-rw-r--r-- | ChangeLog | 5 | ||||
-rw-r--r-- | NEWS | 1 | ||||
-rw-r--r-- | lib/matrix.rb | 14 | ||||
-rw-r--r-- | test/matrix/test_vector.rb | 9 |
4 files changed, 29 insertions, 0 deletions
@@ -1,3 +1,8 @@ +Wed Oct 8 04:29:21 2014 Marc-Andre Lafortune <ruby-core@marc-andre.ca> + + * lib/matrix.rb: Add Vector.basis. + Based on patch by gogo tanaka [#10072] + Tue Oct 7 23:40:16 2014 Nobuyoshi Nakada <nobu@ruby-lang.org> * signal.c (rb_f_kill): get rid of deadlock as unhandled and @@ -84,6 +84,7 @@ with all sufficient information, see the ChangeLog file. which is obtained by multiplying the first minor by (-1)**(row + column). * hstack and vstack are new instance and class methods to stack matrices horizontally and vertically. + * Vector.basis(size:, index:) returns the specified basis vector * Method * New methods: diff --git a/lib/matrix.rb b/lib/matrix.rb index 81834ab898..054c197b52 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -1624,6 +1624,7 @@ end # To create a Vector: # * Vector.[](*array) # * Vector.elements(array, copy = true) +# * Vector.basis(size: n, index: k) # # To access elements: # * #[](i) @@ -1686,6 +1687,19 @@ class Vector end # + # Returns a standard basis +n+-vector, where k is the index. + # + # Vector.basis(size:, index:) # => Vector[0, 1, 0] + # + def Vector.basis(size:, index:) + raise ArgumentError, "invalid size (#{size} for 1..)" if size < 1 + raise ArgumentError, "invalid index (#{index} for 0...#{size})" unless 0 <= index && index < size + array = Array.new(size, 0) + array[index] = 1 + new convert_to_array(array, false) + end + + # # Vector.new is private; use Vector[] or Vector.elements to create. # def initialize(array) diff --git a/test/matrix/test_vector.rb b/test/matrix/test_vector.rb index ced774c490..465108dcec 100644 --- a/test/matrix/test_vector.rb +++ b/test/matrix/test_vector.rb @@ -10,6 +10,15 @@ class TestVector < Test::Unit::TestCase @w1 = Vector[2,3,4] end + def test_basis + assert_equal(Vector[1, 0, 0], Vector.basis(size: 3, index: 0)) + assert_raise(ArgumentError) { Vector.basis(size: -1, index: 2) } + assert_raise(ArgumentError) { Vector.basis(size: 4, index: -1) } + assert_raise(ArgumentError) { Vector.basis(size: 3, index: 3) } + assert_raise(ArgumentError) { Vector.basis(size: 3) } + assert_raise(ArgumentError) { Vector.basis(index: 3) } + end + def test_identity assert_same @v1, @v1 assert_not_same @v1, @v2 |