Skip to content

Instantly share code, notes, and snippets.

@chrismedrela
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismedrela/9346729 to your computer and use it in GitHub Desktop.
Save chrismedrela/9346729 to your computer and use it in GitHub Desktop.
Linear interpolation documentation

Interpolation

breeze.interp module supports interpolation facilities for data in one dimension (univariate interpolation). At this moment, there is only linear interpolation available, but you can easily write your own 1d interpolation facilities.

All examples in this document assumes that you've imported necessary modules:

scala> import breeze.interp._

1D interpolation

1D (univariate) interpolators gets the coordinates of nodes. One vector for each coordinate is required:

scala> val x = DenseVector(0.0, 1.0, 2.0, 3.0)
scala> val y = DenseVector(2.0, 4.0, 8.0, 5.0)
scala> val f = LinearInterpolator(x, y)

Alternatively, you can pass one matrix with two columns, the first representing x coordinates and the second one -- y coordinates:

scala> val m = DenseMatrix((0.0, 1.0, 2.0, 3.0), (2.0, 4.0, 8.0, 5.0))
scala> val f2 = LinearInterpolator(DenseMatrix)

The interpolator returns an interpolating function. You can ask for the value at given point:

scala> f(2.5)
6.5

or at given vector of points:

scala> f(DenseVector(1.0, 1.25, 1.5))
DenseVector(4.0, 5.0, 6.0)

Writing your own 1D interpolator

You need to inherit from breeze.interp.UnivariateInterpolator class and at least implement the apply method that computes value at given point:

class MyInterpolator (val X: Vector[Double],
                      val Y: Vector[Double])
                     extends UnivariateInterpolator[Double, Double](X, Y) {
  def apply(x: Double): Double = ...
}

MyInterpolator automatically inherits matrix-based constructor as well as apply version that computes the values at given vector of points.

@dlwh
Copy link

dlwh commented Mar 6, 2014

I don't know who I feel about the DenseMatrix version, but otherwise this looks good!

I'd prefer the package to be breeze.interpolate, interp could be interpreter or interpolate. Better to err on the side of length when there's ambiguity.

Possibly UnivariateInterpolator should be a pure trait implementation, since one could imagine implementing a "null" interpolator that always returns 0.

@git4sun
Copy link

git4sun commented Apr 28, 2014

How can I import breeze.interp._ ? Any maven entry or libraryDependencies?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment