3C科技 娛樂遊戲 美食旅遊 時尚美妝 親子育兒 生活休閒 金融理財 健康運動 寰宇綜合

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
此篇文章瀏覽量: 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 若覺得文章有幫助,請多分享,讓其他同好也能吸收網站技能知識。 Tweet

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

寫了 5860316篇文章,獲得 23313次喜歡
精彩推薦