summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--ChangeLog5
-rw-r--r--NEWS1
-rw-r--r--lib/matrix.rb14
-rw-r--r--test/matrix/test_vector.rb9
4 files changed, 29 insertions, 0 deletions
diff --git a/ChangeLog b/ChangeLog
index de473c22ee..6c069a0d55 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -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
diff --git a/NEWS b/NEWS
index 62def458df..8222050f93 100644
--- a/NEWS
+++ b/NEWS
@@ -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