I seem unable to find the definition of this macro @.
, or .
itself. I know it's an elementwise operation. But, how could I use it to its fullest is still a secret to me.
For example, JavaScript has the foreach(i,e){} in which you can work with the (i)ndex and the (e)lement etc.
The first step when you do not know how to do something in Julia is to type: ?
followed by your command. In that case you get:
help?> @.
@. expr
Convert every function call or operator in expr into a "dot call" (e.g. convert f(x) to f.(x)), and convert every assignment in expr to a "dot assignment" (e.g. convert += to .+=).
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).
(@. is equivalent to a call to @__dot__.)
Examples
≡≡≡≡≡≡≡≡≡≡
julia> x = 1.0:3.0; y = similar(x);
julia> @. y = x + 3 * sin(x)
3-element Vector{Float64}:
3.5244129544236893
4.727892280477045
3.4233600241796016
Since this is a macro sometimes it is easier to understand using @macroexpand
:
julia> @macroexpand @. y = x + 3 * sin(x)
:(y .= (+).(x, (*).(3, sin.(x))))
While this is using a functional representation (Polish notation) of operators (that is a+b
is written as +(a,b)
) - otherwise it is very clear what has happened! Simply a dot has been added everywhere and now your code is vectorized.