What’s going wrong here, I get a DimensionMismatch error when I run this:
input = repeat([ones(2)], 4)
output = zeros(2)
sum(input) # Gives a 2-element Vector{Float64}
sum!(output, input) # Gives a DimensionMismatch error
The error is:
DimensionMismatch("reduction on array with indices (Base.OneTo(4),) with output with indices (Base.OneTo(2),)")
I can write a fix function for my specific case:
function sum_fixed!(output, input::Vector{Vector{T}}, n, m) where T
for j in 1:m
for i in 1:n
output[j] += input[i][j]
end
end
end
which is (sometimes) non-allocating:
@btime sum_fixed!(output, input, 4, 2)
34.747 ns (0 allocations: 0 bytes)
but I’m still curious as to why the first doesn’t work and why my function sometimes allocates memory as in the case of my function in the context that I want to use it:
using BenchmarkTools
nagents = 4
f_αβ = reshape(repeat([[0.0, 0.0]], nagents * nagents), nagents, nagents)
sum_f_αβ = [0.0, 0.0]
F_α0 = repeat([[0.0, 0.0]], nagents)
@btime begin
for i = 1:$nagents
sum_fixed!($sum_f_αβ, $f_αβ[:, i], $nagents, $2) # 4 (nagents) allocations
@. $F_α[i] = $F_α0[i] + $sum_f_αβ # 0 allocations
end
end
which then gives
297.729 ns (4 allocations: 448 bytes)
Can anyone tell me why there are 4 allocations in that loop?