Skip to content

Commit 0c464c7

Browse files
authored
Mutable sum of array to array (#278)
* Mutable sum of array to array * Add tests * Fix format
1 parent 6f0e699 commit 0c464c7

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

src/implementations/LinearAlgebra.jl

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,25 @@ function operate!(op::Union{typeof(+),typeof(-)}, A::Array, B::AbstractArray)
9494
return broadcast!(op, A, B)
9595
end
9696

97+
function operate_to!(
98+
output::Array,
99+
op::Union{typeof(+),typeof(-)},
100+
A::AbstractArray,
101+
B::AbstractArray,
102+
)
103+
if axes(output) != promote_shape(A, B)
104+
throw(
105+
DimensionMismatch(
106+
"Cannot sum or substract matrices of axes `$(axes(A))` and" *
107+
" `$(axes(B))` into a matrix of axes `$(axes(output))`," *
108+
" expected axes `$(promote_shape(A, B))`.",
109+
),
110+
)
111+
end
112+
# We don't have `MA.broadcast_to!` as it would be exactly `Base.broadcast!`.
113+
return Base.broadcast!(op, output, A, B)
114+
end
115+
97116
# We call `scaling_to_number` as `UniformScaling` do not support broadcasting
98117
function operate!(
99118
op::AddSubMul,

test/matmul.jl

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,13 @@ end
119119
"Cannot sum or substract a matrix of axes `$(axes(B))` into matrix of axes `$(axes(A))`, expected axes `$(axes(B))`.",
120120
)
121121
@test_throws err MA.operate!(+, A, B)
122+
output = zeros(2)
123+
A = zeros(2, 1)
124+
B = zeros(2, 1)
125+
err = DimensionMismatch(
126+
"Cannot sum or substract matrices of axes `$(axes(A))` and `$(axes(B))` into a matrix of axes `$(axes(output))`, expected axes `$(axes(B))`.",
127+
)
128+
@test_throws err MA.operate_to!(output, +, A, B)
122129
end
123130
@testset "unsupported_product" begin
124131
unsupported_product()
@@ -435,3 +442,18 @@ end
435442
@test B == [1 2]
436443
@test D == B * A
437444
end
445+
446+
function test_array_sum(::Type{T}) where {T}
447+
x = zeros(T, 2)
448+
y = copy(x)
449+
z = copy(y)
450+
alloc_test(() -> MA.operate!(+, y, z), 0)
451+
alloc_test(() -> MA.add!!(y, z), 0)
452+
alloc_test(() -> MA.operate_to!(x, +, y, z), 0)
453+
alloc_test(() -> MA.add_to!!(x, y, z), 0)
454+
return
455+
end
456+
457+
@testset "Array sum" begin
458+
test_array_sum(Int)
459+
end

0 commit comments

Comments
 (0)