Loops
Just as any scientific programming language, Julia has different variants to implement loops. The perhaps most common one is the for
loop
for i in 1:N
# loop body
end
Here, Julia performs instructions inside the loop body for . We can modify the iterates by for i in indexStart:increment:indexEnd
. Hence, if we want to iterate from to with an increment of , we have
for i in N:-2:1
# loop body
end
If we want to iterate over a list or vector , we can use for i in v
. In this case, will take values in the vector .
A further loop that can be used is the while
loop, which performs a given instruction as long as a specified condition holds. Our previous example written as a while loop looks like this
while i <= N
# loop body
i = i - 2
end
Create a matrix with entries using a
for
loop.Apply this matrix to a random vector
v = rand(5)
and normalize the result. That is, .Repeat this process using as input (i.e., ) until using a
while
loop.Print out and check against the eigenvalues of using
eigvals(A)
.
using LinearAlgebra
# 1.
N = 5
A = zeros(N,N)
for i in 1:N
for j in 1:N
A[i, j] = (i - j)^2;
end
end
# 2.
v = rand(N);
vNew = A * v / norm(A * v)
#3.
while norm(v - vNew) > 1e-5
v .= vNew
vNew .= A * v ./ norm(A * v)
end
#4.
println("Approximated dominant eigenvalue is $(norm(A * vNew))")
In order to stop a loop or skip an evaluation of the loop body at a specific iteration index, if a certain condition is fulfilled, we can use the break
and continue
commands. The break
command will exit the loop. A simple example is
for i in 1:10
if i > 5
break
end
println("Iteration index is $i")
end
println("Loop stopped.")
Iteration index is 1
Iteration index is 2
Iteration index is 3
Iteration index is 4
Iteration index is 5
Loop stopped.
This will print out the iteration index until a value of is reached, at which point the loop will be exited. The continue
statement allows us to skip an iterate.
for i in 1:10
if i == 5
continue
end
println("Iteration index is $i")
end
Iteration index is 1
Iteration index is 2
Iteration index is 3
Iteration index is 4
Iteration index is 6
Iteration index is 7
Iteration index is 8
Iteration index is 9
Iteration index is 10
This prints out numbers from to but skips the number .
if
statement, loops are not leaky. That is, new variables defined inside a loop will be unknown outside the loop body.