Skip to content

Commit 58215a8

Browse files
authored
Broadcast arithmetic operators for OneElement (#331)
1 parent c7c34aa commit 58215a8

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/oneelement.jl

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,26 @@ end
151151

152152
adjoint(A::OneElementMatrix) = OneElement(adjoint(A.val), reverse(A.ind), reverse(A.axes))
153153
transpose(A::OneElementMatrix) = OneElement(transpose(A.val), reverse(A.ind), reverse(A.axes))
154+
155+
# broadcast
156+
function broadcasted(::DefaultArrayStyle{N}, ::typeof(conj), r::OneElement{<:Any,N}) where {N}
157+
OneElement(conj(r.val), r.ind, axes(r))
158+
end
159+
function broadcasted(::DefaultArrayStyle{N}, ::typeof(real), r::OneElement{<:Any,N}) where {N}
160+
OneElement(real(r.val), r.ind, axes(r))
161+
end
162+
function broadcasted(::DefaultArrayStyle{N}, ::typeof(imag), r::OneElement{<:Any,N}) where {N}
163+
OneElement(imag(r.val), r.ind, axes(r))
164+
end
165+
function broadcasted(::DefaultArrayStyle{N}, ::typeof(^), r::OneElement{<:Any,N}, x::Number) where {N}
166+
OneElement(r.val^x, r.ind, axes(r))
167+
end
168+
function broadcasted(::DefaultArrayStyle{N}, ::typeof(*), r::OneElement{<:Any,N}, x::Number) where {N}
169+
OneElement(r.val*x, r.ind, axes(r))
170+
end
171+
function broadcasted(::DefaultArrayStyle{N}, ::typeof(/), r::OneElement{<:Any,N}, x::Number) where {N}
172+
OneElement(r.val/x, r.ind, axes(r))
173+
end
174+
function broadcasted(::DefaultArrayStyle{N}, ::typeof(\), x::Number, r::OneElement{<:Any,N}) where {N}
175+
OneElement(x \ r.val, r.ind, axes(r))
176+
end

test/runtests.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2218,6 +2218,20 @@ end
22182218
@test A * (2 + 3.0im) === OneElement(val * (2 + 3.0im), (2,2), (3,4)) == B * (2 + 3.0im)
22192219
@test A / (2 + 3.0im) === OneElement(val / (2 + 3.0im), (2,2), (3,4)) == B / (2 + 3.0im)
22202220
end
2221+
2222+
@testset "broadcasting" begin
2223+
for v in (OneElement(2, 3, 4), OneElement(2im, (1,2), (3,4)))
2224+
w = Array(v)
2225+
n = 2
2226+
@test real.(v) == real.(w)
2227+
@test imag.(v) == imag.(w)
2228+
@test conj.(v) == conj.(w)
2229+
@test v .^ n == w .^ n
2230+
@test v .* n == w .* n
2231+
@test v ./ n == w ./ n
2232+
@test n .\ v == n .\ w
2233+
end
2234+
end
22212235
end
22222236

22232237
@testset "repeat" begin

0 commit comments

Comments
 (0)