Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid broadcasting on an argument in Julia

Tags:

julia

Consider this toy version of a very real-life problem:

julia> foo(a,b) = sum(a) + b
foo (generic function with 1 method)

julia> foo.([1,2],[3,4,5])
ERROR: DimensionMismatch("arrays could not be broadcast to a common size")
Stacktrace:
 [1] _bcs1(::Base.OneTo{Int64}, ::Base.OneTo{Int64}) at ./broadcast.jl:70
 [2] _bcs at ./broadcast.jl:63 [inlined]
 [3] broadcast_shape at ./broadcast.jl:57 [inlined] (repeats 2 times)
 [4] broadcast_indices at ./broadcast.jl:53 [inlined]
 [5] broadcast_c at ./broadcast.jl:311 [inlined]
 [6] broadcast(::Function, ::Array{Int64,1}, ::Array{Int64,1}) at ./broadcast.jl:434

I want the above code to return [6,7,8], but that's not happening because the broadcast implied by the dot tries to match up the input vectors of length 2 and 3 and feed scalars into both arguments of foo. How can I avoid this?

like image 550
gTcV Avatar asked Nov 17 '17 08:11

gTcV


1 Answers

Simply wrap the arguments you don't want to broadcast on into a Ref:

julia> foo.(Ref([1,2]),[3,4,5])
3-element Array{Int64,1}:
 6
 7
 8
like image 80
gTcV Avatar answered Nov 09 '22 20:11

gTcV