Broadcasting function over array of structs?

Hi all,

I’m trying to optimize my code by implementing structs instead of just variables. This means changing my functions to receive structs instead of those variables, and I’m trying to broadcast over a particular struct.

I get the error MethodError: no method matching length(::Main.workspace323.Medium) where Medium is a struct of my design.

I have a self-contained Pluto notebook that you can investigate. Feel free to scroll right to the end where the error is displayed.

Basically my question is, how do I broadcast my function over the inputted array of structs?

When you broadcast over some object, the default option is to check its length and use that information for the broadcast shape computation. If you have your own struct that doesn’t have a length you get the error that you see. To get around that you can define Base.broadcastable(m::MyType) = Ref(m) for example, that will treat your struct like a scalar in broadcasting expressions.

5 Likes

You are a godsend, thank you!

That was the last piece I needed for my code, and now it’s super fast! So much faster than looping over variables.