Broadcasting a function with some non-broadcasted inputs


#1

I have a function that takes a matrix and two scalars. The matrix input is identical for each call, but the scalars change with each call. I would like to broadcast over vectors supplying those scalars. Is it possible to inform Julia that a particular function argument is not broadcasted?

e.g.

function foo(values, n, m)
    values .+ n .+ m
end

vals = [1 2 3; 4 5 6]
n = [9, 3]
m = [4, 5]

foo.(values, n, m)

I can assign a local function:

bfoo(n, m) = foo(vals, n, m)
bfoo.(n, m)

Or use map

map(i -> foo(vals, n[i], m[i]), 1:length(n))

It’d be nice to be able to express this more cleanly.


#2

Does Ref(vals) work?


#3

Ah, it does, thank you!


#4

what about foo.((values,), n, m)?


#5

Ref is better, e.g., if you want a number back when n and m are numbers:

julia> foo = +
+ (generic function with 160 methods)

julia> foo.(Ref(1), 2, 3)
6

julia> foo.((1,), 2, 3)
(6,)