Search code examples
matlabinterpolationcurvespline

Using splines() forms problem if x coordinates go from increasing to decreasing


I have two columns with data, x and y. Now I want to connect these data points in the order they appear in the columns. Say I have x=[1 2 3 4 3 2] and y=[3 4 2 1 3 3]. Now if I use spline to create a smooth curve, it 'sorts' the columns in an increasing order. I would like it to just take the data points, thus firstly x(1),y(1) and connect these to x(2), y(2) and so on.

Is this possible?


Solution

  • spline generates a function from the reals to the reals. This means a more general curve cannot be expressed as y = f(x) but we need to parametrize it as (x(t), y(t)):

    x=[1 2 3 4 3 2];
    y=[3 4 2 1 3 3];
    plot(x,y,'o-');
    % cannot be represented as function y=f(x) 
    % because x=2 and 3 have two different y values
    % -> parametrize x and y:
    t = 1:numel(x);
    tt = linspace(min(t), max(t), 1000);;
    tx = spline(t,x,tt);
    ty = spline(t,y,tt);
    hold on
    plot(tx,ty,'-');
    

    enter image description here