Permalink
Browse files

Created #positive_definite? (#561)

  • Loading branch information...
1 parent d545e7f commit a98d7fd5ce5ed399c191e96639f734016d8c2d62 @shardulparab97 shardulparab97 committed with mohawkjohn Mar 22, 2017
Showing with 36 additions and 0 deletions.
  1. +27 −0 lib/nmatrix/math.rb
  2. +9 −0 spec/math_spec.rb
View
@@ -1387,6 +1387,33 @@ def scale(alpha, incx=1, n=nil)
alias :permute_columns :laswp
alias :permute_columns! :laswp!
+
+ #
+ # call-seq:
+ # positive_definite? -> boolean
+ #
+ # A matrix is positive definite if it’s symmetric and all its eigenvalues are positive
+ #
+ # * *Returns* :
+ # - A boolean value telling if the NMatrix is positive definite or not.
+ # * *Raises* :
+ # - +ShapeError+ -> Must be used on square matrices.
+ #
+ def positive_definite?
+ raise(ShapeError, "positive definite calculated only for square matrices") unless
+ self.dim == 2 && self.shape[0] == self.shape[1]
+ ans = true
+ cond = 0
+ while cond != self.cols
+ if self[0..cond, 0..cond].det <= 0
+ ans = false
+ break
+ end
+ cond += 1
+ end
+ ans
+ end
+
protected
# Define the element-wise operations for lists. Note that the __list_map_merged_stored__ iterator returns a Ruby Object
# matrix, which we then cast back to the appropriate type. If you don't want that, you can redefine these functions in
View
@@ -1267,4 +1267,13 @@
end
end
end
+
+ context "#positive_definite?" do
+ it "should return true for positive_definite? matrix" do
+ n = NMatrix.new([3,3], [2, -1, -1,
+ -1, 2, -1,
+ -1, -1, 3])
+ expect(n.positive_definite?).to be_truthy
+ end
+ end
end

0 comments on commit a98d7fd

Please sign in to comment.