summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--ChangeLog4
-rw-r--r--NEWS3
-rw-r--r--lib/matrix.rb27
3 files changed, 33 insertions, 1 deletions
diff --git a/ChangeLog b/ChangeLog
index b6e32cbe61..fd338aed71 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,7 @@
+Sat Jul 9 11:41:03 2011 Marc-Andre Lafortune <ruby-core@marc-andre.ca>
+
+ * lib/matrix.rb: Add Vector#normalize [ruby-dev:43829]
+
Sat Jul 9 09:25:06 2011 Eric Hodel <drbrain@segment7.net>
* enumerator.c: Remove "enumeration sequenced by".
diff --git a/NEWS b/NEWS
index 5f691b8a4a..1bd986f8cc 100644
--- a/NEWS
+++ b/NEWS
@@ -182,7 +182,8 @@ with all sufficient information, see the ChangeLog file.
* Matrix#unitary?
* Matrix#upper_triangular?
* Matrix#zero?
- * Vector#magnitude
+ * Vector#magnitude, #norm
+ * Vector#normalize
* extended methods:
* Matrix#each and #each_with_index can iterate on a subset of the elements
* Matrix#find_index returns [row, column] and can iterate on a subset
diff --git a/lib/matrix.rb b/lib/matrix.rb
index b4ff31a218..360e79f3cc 100644
--- a/lib/matrix.rb
+++ b/lib/matrix.rb
@@ -1517,8 +1517,11 @@ end
# Vector functions:
# * <tt> #inner_product(v) </tt>
# * <tt> #collect </tt>
+# * <tt> #magnitude </tt>
# * <tt> #map </tt>
# * <tt> #map2(v) </tt>
+# * <tt> #norm </tt>
+# * <tt> #normalize </tt>
# * <tt> #r </tt>
# * <tt> #size </tt>
#
@@ -1778,6 +1781,30 @@ class Vector
Math.sqrt(@elements.inject(0) {|v, e| v + e*e})
end
alias r magnitude
+ alias norm magnitude
+
+ #
+ # Like Vector#collect2, but returns a Vector instead of an Array.
+ #
+ def map2(v, &block) # :yield: e1, e2
+ return to_enum(:map2, v) unless block_given?
+ els = collect2(v, &block)
+ Vector.elements(els, false)
+ end
+
+ class ZeroVectorError < StandardError
+ end
+ #
+ # Returns a new vector with the same direction but with norm 1.
+ # v = Vector[5,8,2].normalize
+ # # => Vector[0.5184758473652127, 0.8295613557843402, 0.20739033894608505]
+ # v.norm => 1.0
+ #
+ def normalize
+ n = magnitude
+ raise ZeroVectorError, "Zero vectors can not be normalized" if n == 0
+ self / n
+ end
#--
# CONVERTING