search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

[Julia] 迴圈 - Carlos-Studio

此篇文章瀏覽量: 215

來介紹 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

若覺得文章有幫助,請多分享,讓其他同好也能吸收網站技能知識。



熱門推薦

本文由 carlos-studiocom 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦