# Rosetta Stone of data interpolation

Are you a Matlab/Octave lover? Are you playing with R?

#scientist vs. #DataScientist#scientists vs. #DataScientist#R #octave pic.twitter.com/tggVOJMt5v

— Enrico Brambilla (@SingingSword) January 7, 2019

Ok, let’s play. In this post we’ll use Octave (or Matlab) syntax first.

Once a logical step is implemented, we’ll do the same in R.

## Data generation

Data generation for this exercise is simply the *sine* function. In Octave:

>> x=linspace(0, 99, 100)*2*pi/100; >> y=sin(x); >> whos Variables in the current scope:and then in R:

Attr Name Size Bytes Class ==== ==== ==== ===== ===== x 1x100 800 double y 1x100 800 double

Total is 200 elements using 1600 bytes >> plot(x, y)

R> x <- seq(from = 0, to = 99, by = 1)*2*pi/100 R> y <- sin(x) R> str(x) num [1:100] 0 0.0628 0.1257 0.1885 0.2513 … R> str(y) num [1:100] 0 0.0628 0.1253 0.1874 0.2487 … R> plot(x,y, type=“l”)

The `plot()`

command works in both languages and produces these plots.
Octave is on the left and R is on the right.

Let us prepare the three times oversampled ordinate in Octave:

>> x1=linspace(0, 299, 300)*2*pi/300;and in R:

R> x1 <- seq(from = 0, to = 299, by = 1)*2*pi/300

## Interpolation

Interpolation can be done with various algorithms. We’ll do a linear interpolation.

In Octave:

>> y1=interp1(x, y, x1, “linear”) >> plot(x, y, ‘or’, x1, y1, ‘.g’)producing:

In R you can obtain the same result as:

y1 <- approx(x, y, x1, method = “linear”) R> plot(x, y, type=“p”, main=“AO”) R> plot(x, y, type=“p”, col=“red”, main=“In R”) R> par(new=TRUE) R> plot(y1, pch=“.”, col=“blue”)

Note that y1 in Octave is:

>> whos y1 Variables in the current scope:while in R it’s a list:

Attr Name Size Bytes Class ==== ==== ==== ===== ===== y1 1x300 2400 double

Total is 300 elements using 2400 bytes

R> str(y1) List of 2 $ x: num [1:300] 0 0.0209 0.0419 0.0628 0.0838 … $ y: num [1:300] 0 0.0209 0.0419 0.0628 0.0836 …

In both cases the 2 last samples of y1 are `"NA"`

. In Octave:

>> y1(298:1:300) ans =In R:

-0.062791 NA NA

R> y1$y[298:300] [1] -0.06279052 NA NAand this makes sense as we oversampled three times.

Matlab is a product of Mathworks.

Octave is free software and is largely
compatible with Matlab.

R is free software as well but it does not know *i*.