Cubic spline for non monotonic vector

I am using Spline1D from Dierckx package, and my code is

Ev = [2, 1, 3,4]
sgrid = [0, 1, 2,4]
spl = Spline1D(Ev,sgrid)

The error I got is

Error on entry, no approximation returned. The following conditions
must hold:
1<=k<=5
x[1] < x[2] < ... < x[end]
w[i] > 0.0 for all i

My understanding is that Spline1D does not allow Ev to be non-monotonic. But first I don’t understand why they have this requirement – can’t we do cubic spline on non-monotonic vectors? Second, I was wondering what method I should use for interpolation in this case?

Splines always describe a parameterisation of a curve or surface.

Like a function f(x) cannot have two values for the same x value, a spline cannot have two values for the same input.

If you want to describe an arbitrary curve in 2D, you can do it with a map s: [0,1] \to \mathbb{R}^2 instead where the first component s_1 would describe the non-monotonic X values.

Thank you for the reply. But I’m not sure I get what you mean. What is R^2 supposed to be? Another question is that for each x (sgrid element), I indeed only have 1 value in Ev?

Can you provude a minimal working example (MWE) that reproduces the issue? That would make it much easier to give a concrete advise…

1 Like

Can’t you just sort them before passing to the constructor?

julia> using Dierckx

julia> Ev = [2, 1, 3]; sgrid = [0, 1, 2];

julia> ord = sortperm(Ev)
3-element Vector{Int64}:
 2
 1
 3

julia> spl = Spline1D(Ev[ord],sgrid[ord]; k=2)
Spline1D(knots=[1.0, 3.0], k=2, extrapolation="nearest", residual=0.0)

# Check that spline passes through your points
julia> spl.(Ev) .- sgrid
3-element Vector{Float64}:
 0.0
 0.0
 0.0

Thanks. I just modified my question acccordingly.

1 Like