SS22 Scientific Coding with Julia

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 i=1,,Ni = 1, \ldots, N. We can modify the iterates by for i in indexStart:increment:indexEnd. Hence, if we want to iterate from NN to 11 with an increment of 22, we have

for i in N:-2:1
    # loop body
end

If we want to iterate over a list or vector vv, we can use for i in v. In this case, ii will take values in the vector vv.

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
We want to compute the dominant eigenvalue of a matrix AA. That is, we wish to find the maximal scalar values λ\lambda such that there exists a vector vv which fulfills Av=λvAv = \lambda v.

  1. Create a matrix AR5×5A\in\mathbb{R}^{5 \times 5} with entries Aij=(ij)2A_{ij} = (i-j)^2 using a for loop.

  2. Apply this matrix to a random vector v = rand(5) and normalize the result. That is, vnew=Av/Avv_{\mathrm{new}} = Av/\Vert Av\Vert.

  3. Repeat this process using vnewv_{\mathrm{new}} as input (i.e., vvnewv\leftarrow v_{\mathrm{new}}) until vnewv<105\Vert v_{\mathrm{new}}- v \Vert < 10^{-5} using a while loop.

  4. Print out AvnewA\cdot v_{\mathrm{new}} and check against the eigenvalues of AA using eigvals(A).

Solution

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 i=6i=6 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 11 to 1010 but skips the number 55.

Note that opposed to the if statement, loops are not leaky. That is, new variables defined inside a loop will be unknown outside the loop body.
CC BY-SA 4.0 - Gregor Ehrensperger, Peter Kandolf, Jonas Kusch. Last modified: September 09, 2022. Website built with Franklin.jl and the Julia programming language.