6

Let's suppose I have a 3 by 5 matrix in R:

4  5  5  6  8
3  4  4  5  6
2  3  3  3  4

I would like to interpolate in between these values to create a matrix of size 15 by 25. I would also like to specify if the interpolation is linear, gaussian, etc. How can I do this?

For example, if I have a small matrix like this

2 3
1 3

and I want it to become 3 by 3, then it might look like

  2    2.5   3
  1.5  2.2   3
  1    2     3 
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
CodeGuy
  • 28,427
  • 76
  • 200
  • 317

2 Answers2

6
app <- function(x, n) approx(x, n=n)$y # Or whatever interpolation that you want

apply(t(apply(x, 1, function(x) app(x, nc))), 2, function(x) app(x, nr))
     [,1] [,2] [,3]
[1,]  2.0 2.50    3
[2,]  1.5 2.25    3
[3,]  1.0 2.00    3
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
  • To followup on my comments at my answer: if I'm reading this code correctly, setting `nc` and `nr` to the number of cols/rows you want for the output matrix will allow arbitrary asymmetric expansion. – Carl Witthoft Apr 16 '13 at 20:28
0

Long time ago I wrote a similar toy, except I never got around to defining the interpolation function. There's also raster::disaggregate .

zexpand<-function(inarray, fact=2, interp=FALSE,  ...)  {
# do same analysis of fact to allow one or two values, fact >=1 required, etc.
fact<-as.integer(round(fact))
switch(as.character(length(fact)),
            '1' = xfact<-yfact<-fact,
            '2'= {xfact<-fact[1]; yfact<-fact[2]},
            {xfact<-fact[1]; yfact<-fact[2];warning(' fact is too long. First two values used.')})
if (xfact < 1) { stop('fact[1] must be > 0') } 
if (yfact < 1) { stop('fact[2] must be > 0') }
bigtmp <- matrix(rep(t(inarray), each=xfact), nrow(inarray), ncol(inarray)*xfact, byr=T)  #does column expansion
bigx <- t(matrix(rep((bigtmp),each=yfact),ncol(bigtmp),nrow(bigtmp)*yfact,byr=T))
# the interpolation would go here. Or use interp.loess on output (won't
# handle complex data). Also, look at fields::Tps which probably does
# a much better job anyway.  Just do separately on Re and Im data
return(invisible(bigx))
}
Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73
  • Thanks for the response. How is this different or better than Math Lundberg's answer above? – CodeGuy Apr 16 '13 at 18:06
  • @CodeGuy If I actually put an interpolation function in there (basically replacing the `rep` function which just duplicates rows or columns), it would be doing almost exactly the same thing, except that I allow for different expansions in the column- and row- dimensions. As Matthew wrote, you can swap in whatever interpolator you want in is code as well. – Carl Witthoft Apr 16 '13 at 20:20