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: StaticArrays.jl/SizedArray.jl at b150a8c0eeca4b886a02f2ffb16406653a6aa054 · JuliaArrays/StaticArrays.jl · GitHub ). 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.

For future reference: I finally managed to do what I wanted to do here: Copy and broadcasting for ProductRepr by mateuszbaran · Pull Request #336 · JuliaManifolds/Manifolds.jl · GitHub and it works well enough for me. I hope it’s a good reason to post in this (very old) thread :sweat_smile: .

1 Like