Reputation: 5
I'm writing a C++ program to generate a cubic spline trajectory for a set of points. These points need not be sorted along the x-axis. For example, it may be a circle, etc.
I have found some libraries on the web, for example, the ALGLIB library or a class here https://www.marcusbannerman.co.uk/index.php/home/42-articles/96-cubic-spline-class.html, but all of these libraries sort the data points. I do not need this because what I want to generate is something like a circle. Is there anyway to achieve this?
Upvotes: 0
Views: 3041
Reputation:
The simple, common trick is to use cumulative linear arclength as the parameter. So, if I have a set of points in a curve as simply (x,y) pairs in the plane where x and y are vectors, do this:
t = cumsum([0;sqrt(diff(x(:)).^2 + diff(y(:)).^2)]);
This gives us the cumulative distance along the piecewise linear segments between each pair of points, presented in the order you have them. Fit the spline curve as two separate spline models, thus x(t) and y(t). So you could use interp1, or use the spline or pchip functions directly. Note that pchip and spline will have different properties when you build that interpolant.
Finally, in the event that you really had a closed curve, so that x(1) and x(end) were supposed to be the same, then you would really want to use a spline model with periodic end conditions. I don't know of any implementations for that except in the spline model in my SLM tools, but it is not difficult to do in theory.
Upvotes: 1
Reputation: 13526
Splines are piecewise functions with respect to some independent variable (usually t
, though they seem to use x
in the code you have linked). Since the specific function to be evaluated depends on the control points closest to the input value t
, it make sense to sort the control points by t
so that you can quickly determine the function that needs to be evaluated.
However even if they were not sorted, you still could not create a circle with a single one dimensional spline. Your spline function y = f(t)
only gives you one value for any given t
. If you are graphing y
with respect to t
and want a circle with radius 1 about the origin, you would need f(0)
to equal both 1
and -1
, which doesn't make any sense.
To get something like a circle you instead need a two dimensional spline, or two splines; one for the x
value and one for the y
value. Once you have these two spline functions f(t)
and g(t)
, then you simply evaluate both functions at the same t
and that will give you the x
and y
values of your spline for that t
.
Upvotes: 7