How to broadcast over only certain function arguments?

question

#1

I have a function that takes fixed input arrays and variable scalars to produce a scalar return value. I would like to use the broadcast capability of Julia to turn the variable scalars into arrays, and have it return an array of the same size. Is there a straightforward way to get the broadcast syntax f.() to interpret the input arguments correctly (not attempting to broadcast over the fixed arrays)? Or is there some other clever way using map or broadcast?

For now, I will initialize the return array and just use a for loop.


#2

You can turn one of the arguments into a tuple to consider it as a scalar:

For example (if I understood your question correctly):

f(x,y) = sum(x) + y
f([1,2,3], 4) #-> 10
f([1,2,3], 5) #-> 11

f.([1,2,3], [4,5])    # -> error

f.(([1,2,3],), [4,5]) # -> [10, 11]
                      # this works because ([1,2,3],) is now considered
                      # to be scalar and is broadcasted

Note how in the second case, the array argument [1,2,3] has been turned into a 1-element tuple containing the actual array argument: ([1,2,3],)

It would also have been possible to use Ref([1,2,3]) to achieve the same effect:

f.(Ref([1,2,3]), [4,5]) #-> [10, 11]

#3

Also see this (ongoing) discussion:


#4

Wrapping an argument in Ref(x) also works and is a common idiom for this.


#5

If you want to override the broadcasting behaviour for a particular function, it’s possible by adding a new method to the broadcasted function. However, I’m not sure it’s a particularly advisable thing to do since your function will behave differently to most other functions.

julia> _f(x,y) = sum(x) + y
_f (generic function with 1 method)

julia> f(x, y) = _f(x,y)
f (generic function with 1 method)

julia> Broadcast.broadcasted(::typeof(f), x, y) = broadcast(_f, Ref(x), y)

julia> f.([1,2,3], [4,5])
2-element Array{Int64,1}:
 10
 11

#6

The tuple-wrapping trick seems to work with Julia v0.7. I didn’t have success with the Ref() trick - will need to experiment further.

Thanks!


#7

It is not a “trick”, but part of the semantics of broadcasting. If it does not work, that is a bug, so please provide a self-contained MWE that demonstrates this.