Broadcasting in Julia
One dot vectorizes any function or operator.
mags = [1.2, 3.8, 5.5, 6.9]
# A dot broadcasts any function or operator over each element.
fluxes = 10.0 .^ (-0.4 .* mags)
println(round.(fluxes, digits = 4))
# Comparisons broadcast too, giving a Bool mask.
visible = mags .<= 6.0
println(visible)
println(count(visible), " of ", length(mags), " visible")
# @. dots an entire expression at once.
shifted = @. sqrt(mags + 1)
println(round.(shifted, digits = 2))
How it works
10.0 .^ (-0.4 .* mags)applies elementwise, no loop.mags .<= 6.0broadcasts a comparison into a Bool mask.@.dots every call in the expression at once.
The run, in numbers
- Lines
- 14
- Characters to type
- 413
- Tokens
- 86
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 86 seconds.
Step 1 of 3 in Broadcasting, step 13 of 27 in Language basics.