我有两个文件, 说文件1
x y
0.0 1.0
1.0 2.0
3.0 5.0
和文件 2
x
0.5
1.815
2.5
我想要获得文件 1 的平滑 cspline 插值值,但在文件 2 指定的 x 轴上。 我知道如何设置表格和样本大小并获得由样本大小确定的输出,但我希望在第二个文件指定的点处获得数据点值。有办法做到吗?
假设您有一个名为
data.dat
的文件,其中包含:
# x y
0.000 0.007
1.111 0.013
2.222 0.061
3.333 0.164
4.444 0.250
5.556 0.273
6.667 0.158
7.778 0.061
8.889 0.015
10.000 0.018
你知道这些数据是通过高斯函数来描述的。 在
gnuplot
上可以写成:
g(x) = a*exp(-(x - b)**2/2*c**2)
假设您还有另一个名为
x-values.dat
的文件,其中包含
您想要插值的值。
# x
0.923
1.497
2.357
3.900
4.396
5.696
6.658
7.146
8.851
9.947
您可以使用
fit
命令查找适合数据的 a
、b
和 c
值。
最后,您使用 x-values.dat
作为高斯函数的输入。
# The Gaussian function
g(x) = a*exp(-(x - b)**2/2*c**2)
# Initial values
a = 0.5 # Height of the curve's peak
b = 6.0 # Position of the center of the peak
c = 1.0 # Controls the width of the "bell"
set fit prescale # Helps to fit if there are parameters that
# differ in size by many orders of magnitude
# Performs the fit
fit g(x) 'data.dat' u 1:2 via a, b, c
# The graph itself:
# 1: Data points
# 2: Gaussian function after fit
# 3: Gaussian function using values from 'x_values.dat' as input
plot \
'data.dat' u 1:2 w p pt 5 lc 'black' t 'Data',\
g(x) w l lc 'red' t 'Gaussian',\
'x_values.dat' u 1:(g($1)) w p pt 7 lc 'blue' t 'Interpolation'
当然,在最好的情况下,您有一个模型(即函数),您可以尝试使其适合您的数据,就像@grsousajunior的答案中所做的那样。 没有模型,但仅在指定 x 值处从
cspline
曲线获取插值的情况,可以通过线性插值来完成。下面的脚本改编自此处:How to resample or interpolate data with gnuplot?
顺便说一句,您可以通过
cspline
设置set samples
点的数量,默认为100
。因此,数据块 cpline
中将有 100 个 $CSpline
点,但如果您只需要指定 x 值(在 $InterpolX
中定义)的值,您可能需要尝试下面的脚本。
脚本:(适用于 gnuplot>=5.4.0,2020 年 7 月)
### linear interpolation of c-spline data
reset session
$Data <<EOD
0.0 1.0
1.5 2.0
3.0 5.0
4.0 3.0
# 9.9 NaN
EOD
$InterpolX <<EOD
0.5
1.0
1.815
2.5
3.5
EOD
set table $CSpline
set samples 100
plot $Data u 1:2 smooth cspline
set table $Temp
plot x1=y1=NaN $CSpline u (x0=x1,x1=$1,x0):(y0=y1,y1=$2,y0):(atan2(y1-y0,x1-x0)) w table, \
'+' every ::::0 u (x1):(y1):(0) w table, \
OoR=999 $InterpolX u 1:(0):(OoR) w table
set table $Temp2
plot $Temp u 2:3:1:1 smooth zsort lc var
set table $Interpolated
p = 0 # include original datapoints? 0=no, 1=yes
plot x1=y2=xb=yb=NaN $Temp2 u (x0=x1, x1=$3, y1=$1, a1=$2, \
a1==OoR ? ( y2=yb+(x1-xb)*tan(ab) ) : \
(ab=a1, xb=x1, yb=y1, y2 = x0==x1 ? y1 : p ? yb : ''), x1) : (y2) w table
unset table
set offset 1,1,1,0
plot $Data u 1:2 w lp pt 7 lc "black" ti "original data", \
$CSpline u 1:2 w l lc "blue" ti "cspline", \
$InterpolX u 1:(0):(0):(0.7) w vec lc "web-green" ti "x-values for interpolation", \
$Interpolated u 1:2 w p pt 6 ps 2 lc "red" ti "interpolated cspline"
### end of script
结果: