[Julia] 04. Loops

햄도·2020년 12월 3일
0

Julia tutorial

목록 보기
3/8

Loops

  1. while loops
  2. for loops

while loops

다른 언어의 while문과 다를 건 없다.

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

1

2

3

4

5

6

7

8

9

10

10

for loops

아래 코드에서 fill()은 (m, n)사이즈 array를 0으로 채운다. julia는 이런 내장함수가 많다.

m, n = 5, 5
A = fill(0, (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

for j in 1:n
    for i in 1:m
        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

nested for loop를 위한 syntactic sugar도 존재한다.

B = fill(0, (m,n))
for j in 1:n, i in 1:m
    B[i, j] = i + j
end
B

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

more "Julia" way 라는 array comprehension도 사용할 수 있다. python과 유사하다.

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

Exercises

# 4.1
for i in 1:100
    println(i^2)
end
# 4.2
squares = Dict()
for i in 1:100
> squares[i] = i^2
end

squares
# 4.3
squares_arr = [a^2 for a in 1:100]
profile
developer hamdoe

0개의 댓글