Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions lib/matrix.rb
Original file line number Diff line number Diff line change
Expand Up @@ -827,6 +827,16 @@ def laplace_expansion(row: nil, column: nil)
end
alias_method :cofactor_expansion, :laplace_expansion

#
# Returns the adjoint of the matrix.
#
# Matrix[ [i,1],[2,-i] ].adjoint
# # => -i 2
# # 1 i
#
def adjoint
conjugate.transpose
end

#--
# TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Expand Down Expand Up @@ -984,11 +994,13 @@ def antisymmetric?
#
def unitary?
raise ErrDimensionMismatch unless square?
rows.each_with_index do |row, i|
adj_conj = adjoint

row_count.times do |i|
column_count.times do |j|
s = 0
row_count.times do |k|
s += row[k].conj * rows[k][j]
s += adj_conj[i, k] * self[k, j]
end
return false unless s == (i == j ? 1 : 0)
end
Expand Down
23 changes: 23 additions & 0 deletions test/matrix/test_matrix.rb
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,20 @@ def test_laplace_expansion
assert_raise(RuntimeError) { Matrix.empty(0, 0).laplace_expansion(row: 0) }
end

def test_adjoint
assert_equal(Matrix.empty, Matrix.empty.adjoint)
assert_equal(Matrix[[1]], Matrix[[1]].adjoint)
assert_equal(Matrix[[9,-6],[-3,7]], Matrix[[9,-3],[-6,7]].adjoint)
assert_equal(Matrix[[45,3,-7],[6,-1,0],[-7,0,0]], Matrix[[45,6,-7],[3,-1,0],[-7,0,0]].adjoint)
assert_equal(@m1.transpose, @m1.adjoint)
assert_equal(@m4.transpose, @m4.adjoint)
assert_equal(Matrix[[Complex(1,-2),1], [Complex(0,-1), 2], [0,3]], @c1.adjoint)
assert_equal(@e1.transpose, @e1.adjoint)
assert_equal(@e2.transpose, @e2.adjoint)
assert_equal(Matrix[[0,Complex(0,1)], [Complex(0, -1), 0]], Matrix[[0,Complex(0,1)], [Complex(0, -1), 0]].adjoint)
assert_equal(Matrix[[Complex(0,1), 0], [0, Complex(0,-1)]], Matrix[[Complex(0, -1), 0], [0, Complex(0, 1)]].adjoint)
end

def test_regular?
assert(Matrix[[1, 0], [0, 1]].regular?)
assert(Matrix[[1, 0, 0], [0, 1, 0], [0, 0, 1]].regular?)
Expand All @@ -379,6 +393,15 @@ def test_square?
assert(!Matrix[[1, 0, 0], [0, 1, 0]].square?)
end

def test_unitary?
assert(Matrix[[0,1], [1,0]].unitary?)
assert(Matrix[[0,Complex(0,-1)], [Complex(0,1),0]].unitary?)
assert(Matrix[[1,0], [0, -1]].unitary?)
assert(!Matrix[[1,1], [1,1]].unitary?)
assert(Matrix[[1,0,0,0], [0,0,1,0], [0,1,0,0], [0,0,0,1]].unitary?)
assert(Matrix[[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]].unitary?)
end

def test_mul
assert_equal(Matrix[[2,4],[6,8]], Matrix[[2,4],[6,8]] * Matrix.I(2))
assert_equal(Matrix[[4,8],[12,16]], Matrix[[2,4],[6,8]] * 2)
Expand Down