How to combine @. with broadcasting for 3d array?

I’m new to Julia.

I want to develop code that combines broadcasting with the @macro for a 3D array like the one below. How can I solve this?

function func(a,b,c)
    return sin(a+b+c)
end
func.([0.1, 0.2, 0.3, 0.4], [0.1, 0.2, 0.3, 0.4], [0.1, 0.2, 0.3, 0.4])
@. func.(sys.k_mesh, sys.k_mesh', reshape(sys.k_mesh, 1, 1, :))

By the way, when I use the following code, I get this error:

MethodError: no method matching reshape(::Float64, ::Int64, ::Int64, ::Colon)

Closest candidates are:
  reshape(!Matched::OffsetArrays.OffsetArray, ::Union{Colon, Int64}...)
   @ OffsetArrays ~/.julia/packages/OffsetArrays/rMTtC/src/OffsetArrays.jl:383
  reshape(!Matched::AbstractArray, ::Union{Colon, Int64}...)
   @ Base reshapedarray.jl:118
  reshape(!Matched::AbstractArray, ::Union{Colon, Integer, AbstractUnitRange}...)
   @ OffsetArrays ~/.julia/packages/OffsetArrays/rMTtC/src/OffsetArrays.jl:351
  ...

You are applying reshape per-element of sys.k_mesh, that’s why the error says you can’t reshape a Float64. The docstring for @. notes:

If you want to avoid adding dots for selected function calls in expr, splice those function calls in with $. For example, @. sqrt(abs($sort(x))) is equivalent to sqrt.(abs.(sort(x))) (no
  dot for sort).
1 Like

Note that @. is just a tool to apply broadcasting to every call in an expression, but it is not required for broadcasting. Dots alone are sufficient.

What you wrote would work if you delete the @.. You already broadcasted func by writing the “.” in func.(...), so the @. is not needed (and the @. is broadcasting the reshape, which you didn’t intend).

The vast majority of the time, I just apply dots manually to the parts I want and don’t use @..

3 Likes