Skip to main content
 首页 » 编程设计

python之MATLAB 和 Numpy/Scipy 之间的 3d 插值有什么区别

2024年11月24日10kevingrace

我是一名 MATLAB 用户,我正在尝试翻译 Python 中的一些代码作为一项任务。由于我从我的原始代码中注意到 3d 插值结果中两种语言之间的一些差异,我试图通过分析一个简单的示例来解决这个问题。

我用一些值设置了一个 2x2x2 矩阵(下面称为 blockc),它的坐标在三个向量(X、Y、Z)中。给定一个查询点,我使用 3D 线性插值来查找插值。同样,我在 MATLAB 和 Python 中得到了不同的结果(下面的代码)。

python

import numpy as np 
import scipy.interpolate as si 
 
X,Y,Z =(np.array([1, 2]),np.array([1, 2]),np.array([1, 2])) 
 
a = np.ones((2,2,1)) 
b = np.ones((2,2,1))*2 
 
blocc = np.concatenate((a,b),axis=2) # Matrix with values 
 
blocc[1,0,0]=7 
blocc[0,1,1]=7 
 
qp = np.array([2,1.5,1.5]) #My query point 
 
value=si.interpn((X,Y,Z),blocc,qp,'linear') 
 
print(value) 

这里我得到值=3

编程语言

blocc = zeros(2,2,2); 
blocc(:,:,1) = ones(2,2); 
blocc(:,:,2) = ones(2,2)*2; 
 
blocc(2,1,1)=7; 
blocc(1,2,2)=7; 
 
X=[1,2]; 
Y=[1,2]; 
Z=[1,2]; 
 
qp = [2 1.5 1.5]; 
 
value=interp3(X,Y,Z,blocc,qp(1),qp(2),qp(3),'linear') 

这里的值=2.75

我不明白为什么:我认为关于插值和/或矩阵索引在 Python 中的工作原理我不明白。你能帮我说清楚吗?谢谢!

请您参考如下方法:

显然,对于 MATLAB,当 X、Y 和 Z 是向量时,它认为 values 数组中维度的顺序是 (Y, X, Z)。来自 the documentation :

V — Sample values
array

Sample values, specified as a real or complex array. The size requirements for V depend on the size of X, Y, and Z:

  • If X, Y, and Z are arrays representing a full grid (in meshgrid format), then the size of V matches the size of X, Y, or Z .
  • If X, Y, and Z are grid vectors, then size(V) = [length(Y) length(X) length(Z)].

If V contains complex numbers, then interp3 interpolates the real and imaginary parts separately.

Example: rand(10,10,10)

Data Types: single | double
Complex Number Support: Yes

这意味着,要在 Python 中获得相同的结果,您只需交换查询中的第一个和第二个值:

qp = np.array([1.5, 2, 1.5]) 
f = si.interpn((X, Y, Z), blocc, qp, 'linear') 
print(f) 
# [2.75]