从Matlab到Python的interp2(V,k)

时间:2018-11-16 04:37:55

标签: python matlab matrix scipy interpolation

我正在尝试将此版本的interp2从Matlab转换为Python。 在Matlab中用作

Vq = interp2(V,k)

在矩阵V上执行插值,在该矩阵中,每个原始间隔都被递归细分了k次。向每个分区总共添加2^k-1个元素。 但是我还没有找到该功能的Python替代品。我尝试使用scipy.interpolation.interp2,但仅适用于三个矩阵。

1 个答案:

答案 0 :(得分:1)

我在Forum中发现了这种替代方法,看起来像是一封电子邮件转录本,但是无论如何我都会在这里粘贴答案。

import numpy as np


def interp2d_interleave(z,n):
    '''performs linear interpolation on a grid

    all points are interpolated in one step not recursively

    Parameters
    ----------
    z : 2d array (M,N)
    n : int
    number of points interpolated

    Returns
    -------
    zi : 2d array ((M-1)*n+M, (N-1)*n+N)
        original and linear interpolated values

    '''
    frac = np.atleast_2d(np.arange(0,n+1)/(1.0+n)).T
    zi1 = np.kron(z[:,:-1],np.ones(len(frac))) + np.kron(np.diff(z),frac.T)
    zi1 = np.hstack((zi1,z[:,-1:]))
    zi2 = np.kron(zi1.T[:,:-1],np.ones(len(frac))) + np.kron(np.diff(zi1.T),frac.T)
    zi2 = np.hstack((zi2,zi1.T[:,-1:]))
    return zi2.T

def interp2d_interleave_recursive(z,n):
    '''interpolates by recursively interleaving n times
    '''
    zi = z.copy()
    for ii in range(1,n+1):
        zi = interp2d_interleave(zi,1)
    return zi

应按以下方式使用

xyz = np.zeros((2, 2))
xyz = interp2d_interleave_recursive(xyz, 1)

结果将是: enter image description here