diff --git a/lib/matrix.rb b/lib/matrix.rb index 575eb5c..3b62a07 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -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 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- @@ -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 diff --git a/test/matrix/test_matrix.rb b/test/matrix/test_matrix.rb index 3ecb9d2..288a23b 100644 --- a/test/matrix/test_matrix.rb +++ b/test/matrix/test_matrix.rb @@ -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?) @@ -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)