summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authormarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2014-10-07 19:29:53 +0000
committermarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2014-10-07 19:29:53 +0000
commiteb9c3e7120286163c8dfb4c802ddad8c36c9f0c4 (patch)
tree2c71ee3b67f71ee0eeebfb463d7a0f5ae32c3b31 /lib
parent2ebafed88a665dcaaf4fb58b8c3fd0809db8fa2c (diff)
* 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
Diffstat (limited to 'lib')
-rw-r--r--lib/matrix.rb14
1 files changed, 14 insertions, 0 deletions
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)