[Julia] 迴圈

來介紹 while 及 for 迴圈。

while 迴圈

基本語法:

while *condition*
    *loop body*
end

例1:

n = 0
while n < 10
    n += 1
    println(n)
end
n

例2:跑陣列迴圈

myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]

i = 1
while i <= length(myfriends)
    friend = myfriends[i]
    println("Hi $friend, it's great to see you!")
    i += 1
end

for 迴圈

基本語法:

for *var* in *loop iterable*
    *loop body*
end

例1:

for n in 1:10
    println(n)
end

例2:in 可以改成 等號:

for n = 1:10
    println(n)
end

例3:

myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]

for friend in myfriends
    println("Hi $friend, it's great to see you!")
end

建立基本矩陣

例1:

m, n = 5, 5
A = zeros(m, n)

// 產生結果:
5×5 Array{Int64,2}:
 0  0  0  0  0
 0  0  0  0  0
 0  0  0  0  0
 0  0  0  0  0
 0  0  0  0  0

矩陣某個運算:將列與行的 index 加起來:

for i in 1:m
    for j in 1:n
        A[i, j] = i + j
    end
end
A

// 回傳結果
5×5 Array{Int64,2}:
 2  3  4  5   6
 3  4  5  6   7
 4  5  6  7   8
 5  6  7  8   9
 6  7  8  9  10

例2:

m, n = 5, 5
B = zeros(m, n)

//回傳結果:
5×5 Array{Float64,2}:
 0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0

簡潔的寫法:

for i in 1:m, j in 1:n
    B[i, j] = i + j
end
B

// 回傳結果
5×5 Array{Float64,2}:
 2.0  3.0  4.0  5.0   6.0
 3.0  4.0  5.0  6.0   7.0
 4.0  5.0  6.0  7.0   8.0
 5.0  6.0  7.0  8.0   9.0
 6.0  7.0  8.0  9.0  10.0

更快速的寫法:

C = [i + j for i in 1:m, j in 1:n]

// 回傳:
5×5 Array{Int64,2}:
 2  3  4  5   6
 3  4  5  6   7
 4  5  6  7   8
 5  6  7  8   9
 6  7  8  9  10

其它範例:

for n in 1:10
    A = [i + j for i in 1:n, j in 1:n]
    display(A)
end

您可在此處留言

avatar

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料

  Subscribe  
Notify of