I’m looking for a design pattern that will let me broadcast a function over two input lists, returning a 2D array of the output of the function for all possible pairs from the two lists.
In other words if my input arrays are:
x = [1, 2, 3]
y = ["a", "b"]
I’d like a succinct way to calculate
[ f(1, "a") f(2, "a") f(3, "a";
f(1, "b") f(2, "b") f(3, "b") ]
for an arbitrary function f()
of two inputs.
I’ve played with Iterators.product
a little, but I’m not sure it does exactly what I’d like.
julia> (+).(collect(Iterators.product(1:4, [1, 2])))
ERROR: MethodError: no method matching +(::Tuple{Int64,Int64})
julia> (+).(collect(Iterators.product(1:4, [1, 2]))…)
(20, 12)
I should add that I’m looking for a performant way to do this for my application, so anything that makes additional copies of the data won’t work.
Are there any neat Julia tricks folks know of to do this without a for
loop?