Broadcasting over a struct with two arrays

Hi!

I have a type that looks like

struct A{X1<:AbstractArray, X2<:AbstractArray}
    x1::X1
    x2::X2
end
a = A([1, 2], [1 2; 3 4])
b = A([1, 4], [-1 2; -3 4])

and I’d like to extend broadcasting such that, for example, a .= b .- a is equivalent to

a.x1 .= b.x1 .- a.x1
a.x2 .= b.x2 .- a.x2

Is there any example I can follow to do this? I don’t need to combine broadcasting of objects of type A with objects of other types.

you should switch to “mutable struct” then.

I don’t need to change x1 or x2, only their content.

Have you seen https://docs.julialang.org/en/v1/manual/interfaces/#man-interfaces-broadcasting-1?

Yes, I’ve seen that and it was very helpful when I just needed to forward broadcasting to a single wrapped array (although even then I had to look at the code of StaticArrays to make it work well because for example it does not mention that it’s a good idea to add a new method to Base.dataids like here: https://github.com/JuliaArrays/StaticArrays.jl/blob/b150a8c0eeca4b886a02f2ffb16406653a6aa054/src/SizedArray.jl#L75 ). That’s why I was hoping to just work using a full existing implementation.

Check out

2 Likes

Thanks, I didn’t notice that thread. I’ll try something out.