Skip to content

Commit 6e8f9a1

Browse files
authored
Symmetry check in setindex! for Symmetric/Hermitian (#1317)
Currently, the following works unexpectedly: ```julia julia> A = Symmetric(fill([1 2; 3 4], 3, 3)) 3×3 Symmetric{AbstractMatrix, Matrix{Matrix{Int64}}}: [1 2; 2 4] [1 2; 3 4] [1 2; 3 4] [1 3; 2 4] [1 2; 2 4] [1 2; 3 4] [1 3; 2 4] [1 3; 2 4] [1 2; 2 4] julia> A[1,1] = [1 2; 3 4] 2×2 Matrix{Int64}: 1 2 3 4 julia> A[1,1] 2×2 Symmetric{Int64, Matrix{Int64}}: 1 2 2 4 ``` After this PR, the `setindex!` throws an error if the exact value cannot be used: ```julia julia> A[1,1] = [1 2; 3 4] ERROR: ArgumentError: cannot set a diagonal element of a symmetric matrix to an asymmetric value ```
1 parent 5d3d02a commit 6e8f9a1

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/symmetric.jl

+3-2
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,7 @@ Base._reverse(A::Symmetric, ::Colon) = Symmetric(reverse(A.data), A.uplo == 'U'
266266

267267
@propagate_inbounds function setindex!(A::Symmetric, v, i::Integer, j::Integer)
268268
i == j || throw(ArgumentError("Cannot set a non-diagonal index in a symmetric matrix"))
269+
issymmetric(v) || throw(ArgumentError("cannot set a diagonal element of a symmetric matrix to an asymmetric value"))
269270
setindex!(A.data, v, i, j)
270271
return A
271272
end
@@ -276,8 +277,8 @@ Base._reverse(A::Hermitian, ::Colon) = Hermitian(reverse(A.data), A.uplo == 'U'
276277
@propagate_inbounds function setindex!(A::Hermitian, v, i::Integer, j::Integer)
277278
if i != j
278279
throw(ArgumentError("Cannot set a non-diagonal index in a Hermitian matrix"))
279-
elseif !isreal(v)
280-
throw(ArgumentError("Cannot set a diagonal entry in a Hermitian matrix to a nonreal value"))
280+
elseif !ishermitian(v)
281+
throw(ArgumentError("cannot set a diagonal element of a hermitian matrix to a non-hermitian value"))
281282
else
282283
setindex!(A.data, v, i, j)
283284
end

test/symmetric.jl

+11
Original file line numberDiff line numberDiff line change
@@ -1180,4 +1180,15 @@ end
11801180
end
11811181
end
11821182

1183+
@testset "block-symmetric setindex!" begin
1184+
A = fill([1 2; 3 4], 2, 2)
1185+
v = [1 2; 3 4]
1186+
H = Hermitian(A)
1187+
h_msg = "cannot set a diagonal element of a hermitian matrix to a non-hermitian value"
1188+
@test_throws h_msg H[1,1] = v
1189+
S = Symmetric(A)
1190+
s_msg = "cannot set a diagonal element of a symmetric matrix to an asymmetric value"
1191+
@test_throws s_msg S[1,1] = v
1192+
end
1193+
11831194
end # module TestSymmetric

0 commit comments

Comments
 (0)