Overload broadcasting for custom struct?

If do not exactly understand what you want to achieve.

If you define the * operator for a T3{T} like this:

struct T3{T}
           x::T
           y::T
           z::T
end
import Base.*
function (*)(t3::T3{T}, n::Number) where {T}
    return T3{T}(t3.x*n,t3.y*n,t3.z*n)
end  

Then you can write:


julia> t=T3{Float64}(3,4,5)
T3{Float64}(3.0, 4.0, 5.0)

julia> t*5
T3{Float64}(15.0, 20.0, 25.0)

This can be broadcasted for a collection of t3:


julia> vt=[T3{Float64}(1,2,3),T3{Float64}(4,5,8),T3{Float64}(7,8,9)]
3-element Array{T3{Float64},1}:
 T3{Float64}(1.0, 2.0, 3.0)
 T3{Float64}(4.0, 5.0, 8.0)
 T3{Float64}(7.0, 8.0, 9.0)

julia> vt.*=5
3-element Array{T3{Float64},1}:
 T3{Float64}(5.0, 10.0, 15.0)
 T3{Float64}(20.0, 25.0, 40.0)
 T3{Float64}(35.0, 40.0, 45.0)


2 Likes