Broadcast Multiplication on Custom Type


I’ve created a custom struct named MyNum and want to create broadcast operations on this type, like

a = MyNum(rand(3,2))
b = MyNum(rand(3,2))
c = a .* b

I can’t figure out how to do this.

I’ve been able to do this for standard multiplication like

using Base
function Base.:*(T1::MyNum, T2::MyNum)

Hope someone can help me here.

Broadcasting works on arrays’ elements, so what you have now could work for arrays containing MyNum instances.

If you want to broadcast over MyNum as if it were an AbstractArray wrapping the internal array, you need to implement methods in the AbstractArray interface and make a BroadcastStyle for your custom type so that the output of broadcasting is still your type instead of Array. You don’t need to define new methods for scalar operations like *. There is example code for a wrapper array in this section on broadcasting output type, but it may make more sense if you also read the Abstract Arrays and Customizing Broadcasting sections on that page in their entirety.

(Strictly speaking, broadcasting can be done on types other than AbstractArray, but if you’re doing work on internal arrays, subtyping AbstractArray lets you use existing methods like iterate rather than having to re-implement them yourself.)

1 Like