How to use broadcast?

I have two variables, x and y, and I want to loop through an x, intersect with a y, and return a Vector every time I loop through an x

x=[10,20,30]
y=[50,60,70,80]
function m(i,y)
    n=i:i+50
    return [i,i+50,length(intersect(n,y))]
end
a=[]
for i in x
    push!(a,m(i,y))
end
julia> a
3-element Vector{Any}:
 [10, 60, 2]
 [20, 70, 3]
 [30, 80, 4]

All I can think of is using for and push. Can this be broadcast?

You can do it in the following way (the result is matrix)

julia> x=[10,20,30];

julia> y=[50,60,70,80];

julia> [x x .+ 50 length.(intersect.(range.(x, x.+50), Ref(y)))]
3×3 Matrix{Int64}:
 10  60  2
 20  70  3
 30  80  4

or simply using your function

julia> m.(x, Ref(y))
3-element Vector{Vector{Int64}}:
 [10, 60, 2]
 [20, 70, 3]
 [30, 80, 4]
1 Like

Make sure never to do this. As you can see from your own MWE, the result is a Vector{Any}, which is slow, and also hides information about the contents of the array, which could be helpful in many ways. In your case you should write

a = Vector{Int}[]

Another thing is that you could consider returning a tuple instead from your function:

return (i, i+50, length(intersect(n,y)))

They are more lightweight, and the data will be stored directly inline in your vector, with potential performance benefits. It also makes more ‘sense’, as you always return exactly three values, while vectors are for dynamically sized collections.

Then your output would be

julia> m.(x, Ref(y))
3-element Vector{Tuple{Int64, Int64, Int64}}:
 (10, 60, 2)
 (20, 70, 3)
 (30, 80, 4)
2 Likes