本节介绍Julia语言中的while循环和for循环
while循环
while循环的语法:
while * condition *
* loop body *
end
例如我们可以使用wihle
计算或者迭代一个数组
n = 0
while n < 10
n += 1
println(n)
end
1
2
3
4
5
6
7
8
9
10
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
Hi, Ted, it’s great to see you!
Hi, Robyn, it’s great to see you!
Hi, Barney, it’s great to see you!
Hi, Lily, it’s great to see you!
Hi, Marshall, it’s great to see you!
for循环
for循环的语法:
for *var* in *loop iterable*
*loop body*
end
我们可以使用for循环实现上面while循环的例子
for i in 1:10
println(i)
end
1
2
3
4
5
6
7
8
9
10
myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]
for friend in myfriends
println("Hi $friend, it's great to see you!")
end
Hi Ted, it’s great to see you!
Hi Robyn, it’s great to see you!
Hi Barney, it’s great to see you!
Hi Lily, it’s great to see you!
Hi Marshall, it’s great to see you!
我们可以把for循环语法中的in
改为=
或者∈
for n = 1:10
println(n)
end
1
2
3
4
5
6
7
8
9
10
for n ∈ 1:10
println(n)
end
1
2
3
4
5
6
7
8
9
10
现在让我们使用for循环生成一个数组,这个数组的每一个元素是它对应行数和列数的和。首先初始化一个所有元素都是0的数组
m, n = 5, 5
A = zeros(m, n)
for i in 1:m
for j in 1:n
A[i, j] = i + j
end
end
A
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
下面是同一个嵌套for循环的语法糖(syntactic sugar)
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
使用下面更julia的方法——数组推导(array comprehension)——生成那个数组
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循环中放入数组推导式,生成大小(size)不断增大的矩阵
for n in 1:10
A = [i + j for i in 1:m, j in 1:n]
display(A)
end
5×1 Array{Int64,2}:
2
3
4
5
65×2 Array{Int64,2}:
2 3
3 4
4 5
5 6
6 75×3 Array{Int64,2}:
2 3 4
3 4 5
4 5 6
5 6 7
6 7 85×4 Array{Int64,2}:
2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8
6 7 8 95×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 105×6 Array{Int64,2}:
2 3 4 5 6 7
3 4 5 6 7 8
4 5 6 7 8 9
5 6 7 8 9 10
6 7 8 9 10 115×7 Array{Int64,2}:
2 3 4 5 6 7 8
3 4 5 6 7 8 9
4 5 6 7 8 9 10
5 6 7 8 9 10 11
6 7 8 9 10 11 125×8 Array{Int64,2}:
2 3 4 5 6 7 8 9
3 4 5 6 7 8 9 10
4 5 6 7 8 9 10 11
5 6 7 8 9 10 11 12
6 7 8 9 10 11 12 135×9 Array{Int64,2}:
2 3 4 5 6 7 8 9 10
3 4 5 6 7 8 9 10 11
4 5 6 7 8 9 10 11 12
5 6 7 8 9 10 11 12 13
6 7 8 9 10 11 12 13 145×10 Array{Int64,2}:
2 3 4 5 6 7 8 9 10 11
3 4 5 6 7 8 9 10 11 12
4 5 6 7 8 9 10 11 12 13
5 6 7 8 9 10 11 12 13 14
6 7 8 9 10 11 12 13 14 15
需要注意for
循环的作用域,即变量的可见性。
for kk in 1:4
println(kk)
end
1
2
3
4
如果变量kk
没有在for
循环外面的作用域里引入,在for
循环内定义的变量,它就只在for
循环内部可见,在外部和后面均不可见。
kk
ERROR: UndefVarError: kk not defined