Using CSCVN to interpolate

27 views (last 30 days)
Aurea94
Aurea94 on 23 Feb 2021
Answered: Yash Sharma on 13 Feb 2024
I am trying to use CSCVN function to interpolate a vector between 2 points as shown in figure.
However, even if a obtain the desired curve when using fnplot, I cannot obtain the values of that curve when using FNVAL.
Here is a simple example that shows my problem.
Points=[0,1,2,3;2,1,5,1];
F1=cscvn(Points);
figure
scatter(Points(1,:),Points (2,:))
hold on
fnplt(F1)
grid on
grid minor
x=1.5;
y=fnval(F1,x);
scatter(repmat(x,size(y)),y,'k*')
What shouId I use/do to obtain the (x,y) values of the interpolated spline?
Thank you for your help

Answers (1)

Yash Sharma
Yash Sharma on 13 Feb 2024
Hi,
The cscvn function in MATLAB generates a parametric cubic spline from a set of points. When using this function, the resulting spline is defined not by direct x or y values, but by a parameter t that typically spans from 0 to the number of data points minus one. The output of the spline is a pair of values (x(t), y(t)) for each t. To find a y-coordinate for a specific x-coordinate, like 1.5, you must first determine the corresponding parameter t that yields x(t) = 1.5. Afterward, you can calculate y(t) using this parameter value.
Here's a corrected version of your MATLAB code that uses a simple search to find the approximate t for a given x and then evaluates y at that t. This is a numerical approach and may not be the most efficient, but it should work for your example:
Points = [0, 1, 2, 3; 2, 1, 5, 1];
F1 = cscvn(Points);
figure
scatter(Points(1,:), Points(2,:))
hold on
fnplt(F1)
grid on
grid minor
% The x value we want to find the corresponding y for
target_x = 1.5;
% Obtain the breaks (knots) of the spline
breaks = fnbrk(F1, 'breaks');
% We need to search for the correct parameter t that gives us the x value
% Start by creating a fine grid of t values
t_values = linspace(breaks(1), breaks(end), 1000);
% Evaluate the spline at each t value
xy_values = fnval(F1, t_values);
% Find the index where the x value is closest to our target x
[~, idx] = min(abs(xy_values(1,:) - target_x));
% The corresponding t value is where we have our target x
t_target = t_values(idx);
% Now evaluate the spline at t_target to get the y value
y_target = xy_values(2, idx);
% Plot the point on the curve
scatter(xy_values(1, idx), y_target, 'k*')
Hope it helps!

Tags

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!