Broadcast over matrix dimension for multiple arguments

Say I have 2 matrices, a and b. How can I call a function that expects 2 vectors by broadcasting over their (eg) rows. For example:

function foo(a :: Vector, b :: Vector, c :: Float64)
    return (sum(a) + sum(b)) / c

a = [1 2 3 4; 5 6 7 8]
b = [1 2 3 4; 5 6 7 8]
c = 2.0

Should return a Vector of [10, 26]. Something that does not work but points to how this could be done is using foo.(eachrow(a), eachrow(b), c). Or similarly, mapslices(a->foo(a,b), a, dims=2), even though it does not work either since b is not sliced into vectors.

julia> function foo(a, b, c)
           return (sum(a) + sum(b)) / c

julia> foo.(eachrow(a),eachrow(b),c)
2-element Vector{Float64}:

btw, you probably should drop any and all type annotation, the c::Float64 is clearly too restrictive, and the minimal fix you need is Vector β†’ AbstractVector


It does work, but you sabotage the function by putting in the overly restrictive type annotations.

Ah right, thanks for clarifying!

You can try AbstractVector, or just leave it untyped. Also, Float64 is much more specific than needed. Maybe use Number.

Yeap. Actually I have it now annotated as foo(a :: Vector{T}, b :: Vector{T}, c :: T) where T <: AbstractFloat, which works and it is more case specific for me.

That should not work, since eachrow does not return Vector. Perhaps you have some old definitions there.

1 Like

Spot on… thanks again!