Skip to content
Julia

Broadcasting & Vectorization

Apply a function element-wise over arrays with dot syntax and @.

By EZ4Code Team
broadcastingarraysperformance

Code

# Dot syntax broadcasts any function element-wise
a = [1.0, 2.0, 3.0, 4.0]
b = [10.0, 20.0, 30.0, 40.0]

y = sin.(a) .+ 2.0 .* b        # element-wise sin(a) + 2*b
scale = exp.(a) ./ sum(exp.(a)) # softmax-style normalization

# Broadcasting over a matrix: each column minus its mean
M = rand(3, 4)
means = mean(M, dims=1)         # 1x4 matrix
centered = M .- means           # broadcasts (3x4) .- (1x4)

# @. macro turns every operation into a broadcast
z = @. sin(a)^2 + cos(a)^2      # equals sin.(a).^2 .+ cos.(a).^2

# Broadcasting expands singleton dims automatically
col = rand(3)                   # 3-element vector
row = rand(1, 4)                # 1x4 matrix
outer = col .+ row              # 3x4 result (outer sum)

Explanation

Julia's dot syntax (f.(x), .+, .*) broadcasts any function or operator element-wise, eliminating the need for vectorized wrappers. Unlike MATLAB/NumPy, broadcasting is a syntactic property of the operator, not the function — and it never allocates hidden temporaries when fused with @. This fusion lets Julia generate a single tight loop comparable to hand-written C.

More Julia Snippets