【问题标题】:Error when doing bilinear interpolation with `interp2 {pracma}`; any better way for 2D interpolation?使用“interp2 {pracma}”进行双线性插值时出错;二维插值有更好的方法吗?
【发布时间】:2016-12-08 05:13:57
【问题描述】:

我正在尝试对名为 vol_coarse 的表执行 2d 插值。

install.packages("install.load")
install.load::load_package("pracma", "data.table")

vol_coarse <- data.table(V1 = c(3 / 8, 1 / 2, 3 / 4, 1, 1 + 1 / 2, 2, 3, 6),
V2 = c(0.50, 0.59, 0.66, 0.71, 0.75, 0.78, 0.82, 0.87),
V3 = c(0.48, 0.57, 0.64, 0.69, 0.73, 0.76, 0.80, 0.85),
V4 = c(0.44, 0.53, 0.60, 0.65, 0.69, 0.72, 0.76, 0.81))
setnames(vol_coarse, c("Maximum size of aggregate (in)", "2.40", "2.60", "2.80"))

x <- vol_coarse[, 2][[1]]

y <- as.numeric(colnames(vol_coarse[, 2:ncol(vol_coarse)]))

z <- meshgrid(x, y)

xp <- 3 / 4

yp <- 2.70

interp2(x = x, y = y, Z = z, xp = xp, yp = yp, method = "linear")

这是返回的错误信息:

错误:is.numeric(Z) 不是 TRUE

我在?interp2 中读到:

length(x) = nrow(Z) = 8 and length(y) = ncol(Z) = 3 must be satisfied.

如何创建一个 8 x 3 的矩阵,以便我可以使用 interp2

或者有没有更好的方法来执行这种插值?

谢谢。

【问题讨论】:

    标签: r interpolation bilinear-interpolation


    【解决方案1】:

    如果我没有误会你,你想要:

    x <- c(3 / 8, 1 / 2, 3 / 4, 1, 1 + 1 / 2, 2, 3, 6)  ## V1
    y <- c(2.4, 2.6, 2.8)  ## column names
    Z <- cbind(c(0.50, 0.59, 0.66, 0.71, 0.75, 0.78, 0.82, 0.87),  ## V2
               c(0.48, 0.57, 0.64, 0.69, 0.73, 0.76, 0.80, 0.85),  ## V3
               c(0.44, 0.53, 0.60, 0.65, 0.69, 0.72, 0.76, 0.81))  ## V4
    xp <- 3 / 4
    yp <- 2.70
    

    您已经在网格上有一个定义明确的矩阵。例如,您可以通过以下方式调查您的 3D 数据:

    persp(x, y, Z)
    image(x, y, Z)
    contour(x, y, Z)
    

    我不推荐pracma,因为interp2 函数有一个错误。我建议使用 fields 包中的 interp.surface 函数在网格上进行插值。

    library(fields)
    ## the list MUST has name `x`, `y`, `x`!
    ## i.e., unnamed list `list(x, y, Z)` does not work!
    interp.surface(list(x = x, y = y, z = Z), cbind(xp, yp))
    # [1] 0.62
    

    来自pracmainterp2 不一致。手册上说Z 矩阵是length(x) by length(y),但该函数确实检查Z 必须是length(y) by length(x)

    ## from manual
    
       Z: numeric ‘length(x)’-by-‘length(y)’ matrix.
    
    ## from source code of `interp2`
    
       lx <- length(x)
       ly <- length(y)
       if (ncol(Z) != lx || nrow(Z) != ly) 
           stop("Required: 'length(x) = ncol(Z)' and 'length(y) = nrow(Z)'.")
    

    所以,为了使interp2 工作,你必须传入Z 的转置:

    interp2(x, y, t(Z), xp, yp)
    # [1] 0.62
    

    或反向 xy(还有 xpyp 也是!!):

    interp2(y, x, Z, yp, xp)
    # [1] 0.62
    

    这与我们使用imagecontourpersp 的方式确实不一致。

    【讨论】:

    • 感谢您的详细解释。这个答案很有帮助。
    猜你喜欢
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2018-02-09
    • 1970-01-01
    • 2016-06-22
    • 2021-04-12
    相关资源
    最近更新 更多