Interpolations パッケージを使うとデータを補間することができます。
ドキュメントに書いてある通り、次のようにしてインストールします。(パッケージモードで add Interpolations を実行しても同じです)
julia> using Pkg julia> Pkg.add("Interpolations")
線形補間の使用例
次のサンプルは単純な線形補間で与えられたデータ (ベクトル A) の成分間を保管してグラフを描くものです。
using Interpolations using Plots xs = range(0, 10, step=1) A = [0.1, 1.8, 2.2, 2.6, 5.1, 4.2, 5.9, 7.5, 8.8, 9.0, 9.9] println("LinearInterpolation") itp = LinearInterpolation(xs, A) y1 = Float64[] x1 = range(0.0, 10.0, step=0.02) for x = x1 append!(y1, itp(x)) end plot(x1, y1, show=true, w=2) print("> ") read(stdin, Char)
B-スプライン曲線で補間する
描画ソフトなどでよく見かけるB-スプライン曲線での補間を行ってみます。
次のサンプルは Interpolations のドキュメントに出ていたサンプルを少し改造およびコメントを英語から日本語にしてしてグラフを表示するものです。
using Interpolations, Plots println("Start Interpolations and Plot") # 補間範囲の最小値と最大値 a = 1.0 b = 10.0 # 補間区間を決める x = a:1.0:b # x と y の長さは同じで要素は昇順であること。 # length(x) == length(y) y = @. cos(x^2 / 9.0) # 補間対象の点のY座標を生成 # データから線形と3次スプライン関数を生成する。 itp_linear = LinearInterpolation(x, y) itp_cubic = CubicSplineInterpolation(x, y) # 補間関数が破壊型 plot! で正しく動くようにするため f_linear(x) = itp_linear(x) f_cubic(x) = itp_cubic(x) # Plots の表示パラメータ width, height = 720, 480 # ウィンドウサイズ (なくても動作する) x_new = a:0.1:b # 曲線を滑らかにするための設定 (3次スプライン補間で必要) # 散布図 (点の描画) scatter(x, y, markersize=7,label="Data points") # 線形補間グラフ plot!(f_linear, x_new, w=3,label="Linear interpolation") # 3次スプライン補間のグラフ plot!(f_cubic, x_new, linestyle=:dash, w=3, label="Cubic Spline interpolation") # ウィンドウサイズを設定 plot!(size = (width, height)) # 凡例の表示とウィンドウ表示の指定 plot!(legend = :bottomleft, show=true) print("> ") read(stdin, Char)