LoginSignup
1
0

More than 1 year has passed since last update.

【超個人的備忘録】julia の . の使い方

Last updated at Posted at 2020-09-16

julia では . を使ってベクトル化できるらしい

公式docでは,以下のように言っている.

In technical-computing languages, it is common to have "vectorized" versions of functions, which simply apply a given function f(x) to each element of an array A to yield a new array via f(A). This kind of syntax is convenient for data processing, but in other languages vectorization is also often required for performance: if loops are slow, the "vectorized" version of a function can call fast library code written in a low-level language. In Julia, vectorized functions are not required for performance, and indeed it is often beneficial to write your own loops (see Performance Tips), but they can still be convenient. Therefore, any Julia function f can be applied elementwise to any array (or other collection) with the syntax f.(A).

どういうこと?

実際にコードを書いてみよう.

vectorize.jl
julia> A = [1.0 , 2.0 , 3.0]
3-element Array{Float64,1}:
 1.0
 2.0
 3.0

julia> sin(A) #配列を代入している.これだとエラーを吐く.
ERROR: MethodError: no method matching sin(::Array{Float64,1})
Closest candidates are:
  sin(::BigFloat) at mpfr.jl:727
  sin(::Missing) at math.jl:1197
  sin(::Complex{Float16}) at math.jl:1145
  ...
Stacktrace:
 [1] top-level scope at REPL[2]:1

julia> sin.(A) #このように . を用いると配列を代入できる.
3-element Array{Float64,1}:
 0.8414709848078965
 0.9092974268256817
 0.1411200080598672

上で見るように,. を用いると配列すなわちベクトル成分を代入できる.

もう1つ例を

こちらの方がイメージしやすかったかもしれない.

vectorize.jl
julia> f(x,y) = 3x + 4y
f (generic function with 1 method)

julia> A = [1.0 , 2.0 , 3.0]
3-element Array{Float64,1}:
 1.0
 2.0
 3.0

julia> B = [4.0 , 5.0 , 6.0]
3-element Array{Float64,1}:
 4.0
 5.0
 6.0

julia> f.(π , A)
3-element Array{Float64,1}:
 13.42477796076938
 17.42477796076938
 21.42477796076938

julia> f.(A , B)
3-element Array{Float64,1}:
 19.0
 26.0
 33.0
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0