Skip to content

Symmetry check in setindex! for Symmetric/Hermitian #1317

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 27, 2025
Merged
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
5 changes: 3 additions & 2 deletions src/symmetric.jl
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ Base._reverse(A::Symmetric, ::Colon) = Symmetric(reverse(A.data), A.uplo == 'U'

@propagate_inbounds function setindex!(A::Symmetric, v, i::Integer, j::Integer)
i == j || throw(ArgumentError("Cannot set a non-diagonal index in a symmetric matrix"))
issymmetric(v) || throw(ArgumentError("cannot set a diagonal element of a symmetric matrix to an asymmetric value"))
setindex!(A.data, v, i, j)
return A
end
Expand All @@ -276,8 +277,8 @@ Base._reverse(A::Hermitian, ::Colon) = Hermitian(reverse(A.data), A.uplo == 'U'
@propagate_inbounds function setindex!(A::Hermitian, v, i::Integer, j::Integer)
if i != j
throw(ArgumentError("Cannot set a non-diagonal index in a Hermitian matrix"))
elseif !isreal(v)
throw(ArgumentError("Cannot set a diagonal entry in a Hermitian matrix to a nonreal value"))
elseif !ishermitian(v)
throw(ArgumentError("cannot set a diagonal element of a hermitian matrix to a non-hermitian value"))
else
setindex!(A.data, v, i, j)
end
Expand Down
11 changes: 11 additions & 0 deletions test/symmetric.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1180,4 +1180,15 @@ end
end
end

@testset "block-symmetric setindex!" begin
A = fill([1 2; 3 4], 2, 2)
v = [1 2; 3 4]
H = Hermitian(A)
h_msg = "cannot set a diagonal element of a hermitian matrix to a non-hermitian value"
@test_throws h_msg H[1,1] = v
S = Symmetric(A)
s_msg = "cannot set a diagonal element of a symmetric matrix to an asymmetric value"
@test_throws s_msg S[1,1] = v
end

end # module TestSymmetric