interpolation with matrices in R

徘徊边缘 提交于 2021-02-10 18:53:58

问题


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.


回答1:


You could just put all objects into a list

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

and use 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 ...


来源:https://stackoverflow.com/questions/51597482/interpolation-with-matrices-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!