Skip to content

Commit a98d7fd

Browse files
shardulparab97translunar
authored andcommitted
Created #positive_definite? (#561)
1 parent d545e7f commit a98d7fd

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

lib/nmatrix/math.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1387,6 +1387,33 @@ def scale(alpha, incx=1, n=nil)
13871387
alias :permute_columns :laswp
13881388
alias :permute_columns! :laswp!
13891389

1390+
1391+
#
1392+
# call-seq:
1393+
# positive_definite? -> boolean
1394+
#
1395+
# A matrix is positive definite if it’s symmetric and all its eigenvalues are positive
1396+
#
1397+
# * *Returns* :
1398+
# - A boolean value telling if the NMatrix is positive definite or not.
1399+
# * *Raises* :
1400+
# - +ShapeError+ -> Must be used on square matrices.
1401+
#
1402+
def positive_definite?
1403+
raise(ShapeError, "positive definite calculated only for square matrices") unless
1404+
self.dim == 2 && self.shape[0] == self.shape[1]
1405+
ans = true
1406+
cond = 0
1407+
while cond != self.cols
1408+
if self[0..cond, 0..cond].det <= 0
1409+
ans = false
1410+
break
1411+
end
1412+
cond += 1
1413+
end
1414+
ans
1415+
end
1416+
13901417
protected
13911418
# Define the element-wise operations for lists. Note that the __list_map_merged_stored__ iterator returns a Ruby Object
13921419
# matrix, which we then cast back to the appropriate type. If you don't want that, you can redefine these functions in

spec/math_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1267,4 +1267,13 @@
12671267
end
12681268
end
12691269
end
1270+
1271+
context "#positive_definite?" do
1272+
it "should return true for positive_definite? matrix" do
1273+
n = NMatrix.new([3,3], [2, -1, -1,
1274+
-1, 2, -1,
1275+
-1, -1, 3])
1276+
expect(n.positive_definite?).to be_truthy
1277+
end
1278+
end
12701279
end

0 commit comments

Comments
 (0)