Skip to content

Commit 864aa15

Browse files
committed
Define arithmetic operations on Symmetric/Hermitian with Number
1 parent 93a1f58 commit 864aa15

File tree

2 files changed

+15
-12
lines changed

2 files changed

+15
-12
lines changed

base/linalg/symmetric.jl

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -108,21 +108,14 @@ end
108108
end
109109

110110
function setindex!(A::Symmetric, v, i::Integer, j::Integer)
111-
if (A.uplo == 'U' && i >= j) || (A.uplo == 'L' && i <= j)
112-
setindex!(A.data, v, i, j)
113-
else
114-
setindex!(A.data, v, j, i)
115-
end
111+
i == j || throw(ArgumentError("Cannot set a non-diagonal index in a symmetric matrix"))
112+
setindex!(A.data, v, i, j)
116113
end
117114

118115
function setindex!(A::Hermitian, v, i::Integer, j::Integer)
119-
if i == j && !isreal(v)
120-
throw(ArgumentError("Cannot set a nonreal value to the diagonal in a Hermitian matrix"))
121-
elseif (A.uplo == 'U' && i >= j) || (A.uplo == 'L' && i <= j)
122-
setindex!(A.data, v, i, j)
123-
else
124-
setindex!(A.data, v, j, i)
125-
end
116+
i == j || throw(ArgumentError("Cannot set a non-diagonal index in a Hermitian matrix"))
117+
isreal(v) || throw(ArgumentError("Cannot set a nonreal value to the diagonal in a Hermitian matrix"))
118+
setindex!(A.data, v, i, j)
126119
end
127120

128121
similar{T}(A::Symmetric, ::Type{T}) = Symmetric(similar(A.data, T))
@@ -255,6 +248,10 @@ A_mul_B!{T<:BlasComplex,S<:StridedMatrix}(C::StridedMatrix{T}, A::StridedMatrix{
255248
*(A::HermOrSym, B::HermOrSym) = full(A)*full(B)
256249
*(A::StridedMatrix, B::HermOrSym) = A*full(B)
257250

251+
for T in (:Symmetric, :Hermitian), op in (:+, :-, :*, :/)
252+
@eval ($op)(A::$T, x::Number) = ($T)(($op)(A.data, x), Symbol(A.uplo))
253+
end
254+
258255
bkfact(A::HermOrSym) = bkfact(A.data, Symbol(A.uplo), issymmetric(A))
259256
factorize(A::HermOrSym) = bkfact(A)
260257

test/linalg/symmetric.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,10 +266,16 @@ let X = sparse([1 -1; -1 1])
266266

267267
W[1,1] = 4
268268
@test W == T(sparse([4 -1; -1 1]))
269+
@test_throws ArgumentError (W[1,2] = 2)
269270

270271
@test Y + I == T(sparse([2 -1; -1 2]))
271272
@test Y - I == T(sparse([0 -1; -1 0]))
273+
@test Y * I == Y
274+
272275
@test Y + 1 == T(sparse([2 0; 0 2]))
276+
@test Y - 1 == T(sparse([0 -2; -2 0]))
277+
@test Y * 2 == T(sparse([2 -2; -2 2]))
278+
@test Y / 1 == Y
273279
end
274280

275281
@test_throws ArgumentError Hermitian(X) + 2im*I

0 commit comments

Comments
 (0)