I am trying to interpolate linearly in R.
u = interp1(u, linspace(1, numel(u), numel(u)-1));
y <- x
interp1(x, y, xi, method = "linear")
List of 2
$ : num [1:3] 1 2 3
$ : num [1:2] 1 2
num [1:2] 0 1
Error in interp1(x, y, xi, method = "linear") :
Points 'xi' outside of range of argument 'x'.
library("pracma") # http://finzi.psych.upenn.edu/library/pracma/html/interp1.html
files <- vector("list", 2)
files[] <- c(1,2,3)
files[] <- c(1,2)
# Wanted, MATLAB: u = interp1(u, linspace(1, numel(u), numel(u)-1));
xi <- seq(0,1, len = length(files[]) - 1)
x <- files[]
y <- files[]
files[] <- interp1(x, y, xi, method = "linear")
If you're willing to get
NA values on extrapolation, as is the default for linear interpolation/extrapolation in interp1, then
approx() works fine:
files <- list(1:3,1:2) xi <- seq(0,1, len = length(files[]) - 1) x <- files[] y <- files[] a <- approx(x,y,xi)
You said you wanted just a two-element vector so presumably you just want the output y-values:
a$y ##  NA 1
This may seem wrong, but is the correct answer to the question you actually posed. You've used
files[] for both
approx() should return y=x when the input is in the range from 1 to 3, and
NA otherwise. In this case
[0 1], so the first element is out of the range of the x/y data provided ...
PS I can appreciate wanting to use
pracma for similarity to MATLAB's syntax, but - although
pracma is high-quality and widely used - base R functions are even more widely used/thoroughly tested ...