* lib/matrix.rb: Add Vector.basis.

Based on patch by gogo tanaka [#10072]

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@47833 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
marcandre 2014-10-07 19:29:53 +00:00
parent 2ebafed88a
commit eb9c3e7120
4 changed files with 29 additions and 0 deletions

View File

@ -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

1
NEWS
View File

@ -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:

View File

@ -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)
@ -1685,6 +1686,19 @@ class Vector
new convert_to_array(array, copy)
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.
#

View File

@ -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