# Broadcasting function over array of structs?

**URL:** <https://discourse.julialang.org/t/broadcasting-function-over-array-of-structs/47005>\
**Category:** New to Julia\
**Tags:** question\
**Created:** [September 21, 2020, 1:08pm UTC](https://discourse.julialang.org/t/broadcasting-function-over-array-of-structs/47005 "2020-09-21T13:08:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![kapple](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kapple/32/218915_2.png) [@kapple](https://discourse.julialang.org/u/kapple)\
**Post date:** [September 21, 2020, 1:08pm UTC](https://discourse.julialang.org/t/broadcasting-function-over-array-of-structs/47005/1 "2020-09-21T13:08:28Z")

</div>

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](https://github.com/kapple19/OceanAcousticsModelling/blob/master/src/Pluto_RayTracing.jl) 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?

---

<div class="post-metadata">

**Author:** ![jules](https://avatars.discourse-cdn.com/v4/letter/j/41988e/32.png) [@jules](https://discourse.julialang.org/u/jules)\
**Post date:** [September 21, 2020, 1:19pm UTC](https://discourse.julialang.org/t/broadcasting-function-over-array-of-structs/47005/2 "2020-09-21T13:19:12Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![kapple](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kapple/32/218915_2.png) [@kapple](https://discourse.julialang.org/u/kapple)\
**Post date:** [September 21, 2020, 1:45pm UTC](https://discourse.julialang.org/t/broadcasting-function-over-array-of-structs/47005/3 "2020-09-21T13:45:28Z")

</div>

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.
