Julia Loops and Vectorization
Vectorization is doing the same operation on every item of a list in one step. It replaces a written loop with one operation over the whole list.
A loop and a built-in sum give the same total
loop_total adds the items one at a time. The two printed totals match.
function loop_total(a)
total = 0
for x in a
total += x
end
return total
end
a = [1, 2, 3, 4]
println(loop_total(a))
println(sum(a))A vectorized step makes a new list
The dot step adds 10 to every item at once. The printed list and its length prove the result.
a = [1, 2, 3]
b = a .+ 10
println(b)
println(length(b))A vectorized step leaves the old list unchanged
The dot step multiplies every item by 3. The old list prints first, and the new list prints second.
a = [2, 4]
b = a .* 3
println(a)
println(b)Example
function loop_total(a)
total = 0
for x in a
total += x
end
return total
end
a = [5, 10, 15]
doubled = a .* 2
println(loop_total(a))
println(sum(doubled))
println(length(doubled))Key points
- Vectorized operation: a vectorized operation applies one step to every item at once.
- Loop total: a loop inside a function adds items one at a time and gives the same total as a built-in sum.
- Broadcast step: a dot before an operator applies it to every item of a list.
- New list: a broadcast step makes a new list and leaves the old list unchanged.
- Use a broadcast step to change every item without writing a loop.
In this example, loop_total adds the original list, a vectorized step doubles every item, and the printed totals and length show both results.
Note
Julia writes a broadcast step with a dot, as in a .+ 1.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does a .+ 1 do to a list?