Methods for Calculating Arrays Column-wise in Julia
Code
There are methods like map
, broadcast, and comprehension for calculating arrays by column or row.
julia> using Statistics
julia> X = stack([i*ones(8) for i ∈ 1:9], dims=2)
8×9 Matrix{Float64}:
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
# map
julia> map(mean, eachcol(X))
9-element Vector{Float64}:
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
julia> map(eachcol(X)) do col
mean(col)
end
9-element Vector{Float64}:
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
# 브로드캐스트
julia> mean.(eachcol(X))
9-element Vector{Float64}:
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
# 컴프리헨션
julia> [mean(col) for col ∈ eachcol(X)]
9-element Vector{Float64}:
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
Differences1
Generally, there is no performance difference between map and comprehension. The difference lies in the returned value. Map returns a tuple when the iterator is given as a tuple.
julia> X = (1, 2, 3, 4, 5)
(1, 2, 3, 4, 5)
julia> [x^2 for x ∈ X]
5-element Vector{Int64}:
1
4
9
16
25
julia> map(x->x^2, X)
(1, 4, 9, 16, 25)
To obtain a tuple using comprehension,
julia> (x^2 for x ∈ X).iter
(1, 2, 3, 4, 5)
Environment
- OS: Windows11
- Version: Julia 1.10.0
Bogumił Kamiński, 데이터 분석을 위한 줄리아(Julia for Data Analysis, 류현지 역), p92 ↩︎