来自Interpolations.jl的MATLAB样式griddedInterpolant用法

时间:2016-03-06 04:55:27

标签: matlab multidimensional-array interpolation julia

我试图将我的MATLAB程序转换为Julia。该程序的一个关键特性是使用MATLAB中的griddedInterpolant函数。我找到了Julia替换(Interpolations.jl),我在二维情况下做了一个简单的测试,以确保我理解它是如何工作的。这个特殊的程序虽然使用了4-D阵列,但我似乎无法弄清楚如何使用超过2维的Interpolations.jl方法。

MATLAB行为的一个非常简单的例子。请注意,这是一个简单的例子,因为V是平坦的,但你明白了。我的计划将在循环中更改Vkp1gvkp2gv的值。

nK_1 = 50;
nK_2 = 50;
nKP_1 = 10;
nKP_2 = 10;
K1 = linspace(0,100,nK_1);
K2 = linspace(0,100,nK_2);
KP1 = linspace(0,100,nKP_1);
KP2 = linspace(0,100,nKP_1);

nX = 3;
nY = 3;
X = [0.9,1,1.1];
Y = [0.95,1,1.05];

[k1gv,k2gv,xgv,ygv] = ndgrid(K1,K2,X,Y);  % creates grid vectors
V = ones(nK_1,nK_2,nX,nY);    % value func to be interpolated
Fit = griddedInterpolant(k1gv,k2gv,xgv,ygv,V,'linear');   % fitted val fun


[kp1gv,kp2gv,xpgv,ypgv,kk1,kk2] = ndgrid(KP1,KP2,X,Y,K1,K2);
Fitted = Fit(kp1gv,kp2gv,xpgv,ypgv);

我正在寻找的是在Julia中复制它,或者完全像在MATLAB中一样,或者通过重写它来更快。这是我现在的尝试:

nK_1 = 50
nK_2 = 50
nKP_1 = 10
nKP_2 = 10
K1 = linspace(0,100,nK_1)
K2 = linspace(0,100,nK_2)
KP1 = linspace(0,100,nKP_1)
KP2 = linspace(0,100,nKP_1)

nX = 3
nY = 3
X = [0.9,1,1.1]
Y = [0.95,1,1.05]

V = ones(nK_1,nK_2,nX,nY)

# using the more compact notation here, would be similar to
# griddedInterpolant({K1,K2,X,Y},V,'linear') -- no issues with this fit
Fit = interpolate((K1,K2,X,Y),V,Gridded(Linear()))

# this is how I'm getting ndgrid functionality
KP1gv = Float64[i for i in KP1, j in KP2, x in X, y in Y, a in K1, b in K2]
KP2gv = Float64[j for i in KP1, j in KP2, x in X, y in Y, a in K1, b in K2]
Xgv = Float64[x for i in KP1, j in KP2, x in X, y in Y, a in K1, b in K2]
Ygv = Float64[y for i in KP1, j in KP2, x in X, y in Y, a in K1, b in K2]

# what I want to work
Fitted = Fit[KP1gv,KP2gv,Xgv,Ygv]

我已经阅读了有关Interpolations.jl的文档,我知道这应该是可行的,我似乎无法让它发挥作用。

1 个答案:

答案 0 :(得分:1)

不是构造所有那些ndgrid坐标数组,而是执行此操作:

fitted = [Fit[i,j,k,l] for i in KP1, j in KP2, k in X, l in Y]

但有几个提示:

  • 任何对性能至关重要的内容(如上面一行)都应该放在一个函数中。这绝对至关重要。请参阅手册的performance tips页。
  • 这似乎没有详细记录,但Gridded是针对您有矩形网格但间距可能不规则的情况而设计的。如果是常规间距,您可以使用

    做得更好

    itp = interpolate(V,Linear(),OnGrid()) sitp = scale(itp,K1,K2,x,y)

其中xy也是linspace个对象。