用R中的矩阵进行插值 [英] interpolation with matrices in R

查看:50
本文介绍了用R中的矩阵进行插值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用线性插值从2个较小的矩阵中创建一个较大的矩阵.我可以使用这样的函数来做到这一点:

I want to use linear interpolation to create a large matrix from 2 smaller matrices. I can do this using a function like this:

mat1 <- matrix(rep(20, 4), ncol = 2)
mat2 <- matrix(seq(21, 24, 1), ncol = 2)
mat3 <- matrix(c(18, 27, 25, 12), ncol = 2)

num.days <- c(31, 29)

interpolate <- function(initial, final, n){
  data.list <- list()
  for (i in 1:(n - 1)){
    step1 <- (final - initial) / n
    step2 <- step1 * i
    data.list[[1]] <- initial
    data.list[[i+1]] <- round(step2 + initial, 2)
  }
  newmat = do.call(cbind, data.list)
  return(newmat)
}


interpolate(mat1, mat2, num.days[1])
interpolate(mat2, mat3, num.days[2])

我想修改此代码,以便在许多矩阵上迭代执行此函数.我试过将矩阵放在列表中,然后重写函数以在列表中的每个矩阵之间进行插值,但一直无法使其工作.任何帮助或建议,我们将不胜感激.谢谢.

I want to modify this code so that this function is performed iteratively over many matrices. I've tried putting the matrices in a list and rewriting the function to interpolate between each matrix within the list but haven't been able to get it to work. Any help or suggestions are greatly appreciated. Thanks.

推荐答案

您可以将所有对象放入列表中

You could just put all objects into a list

l <- list(mat1, mat2, mat3, num.days)

并使用 lapply()

lapply(1:length(l[[4]]), function(x) interpolate(l[[x]], l[[x + 1]], l[[4]][x]))

屈服

Yielding

List of 2
 $ : num [1:2, 1:62] 20 20 20 20 20 ...
 $ : num [1:2, 1:58] 21 22 23 24 20.9 ...

这篇关于用R中的矩阵进行插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆