Julia 可以用如 Python、R、C等语言的一般语法结构实现 For 循环,但 Julia 还有它自己的更简洁更有意思的方式。
先生成一个 Array:
1 | m, n = 5, 5 |
Output:
1 | 5×5 Array{Int64,2}: |
Normal loop:
1 | for i in 1:m |
Output:
1 | 5×5 Array{Int64,2}: |
syntactic sugar
for the same nested for
loop
1 | for i in 1:m, j in 1:n |
Output:
1 | 5×5 Array{Int64,2}: |
看,i和j可以放在一个for
里!还有更简单的:
The more "Julia" way
1 | C = [i + j for i in 1:m, j in 1:n] |
Output:
1 | 5×5 Array{Int64,2}: |
Cool! 两个循环,一行搞定!