简体   繁体   中英

Cubic spline implementation in Matlab

I have two vectors, x and y that are defined(at random) as follows: x1=[1000 3000 5000 6000 4000 2000 500 0 -1000 -3000 -5000 -6000 -4000 -2000 -500 1 999 2999 4999]; y1=[5000 4999 4990 3500 2500 2499 2498 2497 2496 2495 2494 1000 -1000 -999 -998 -997 -996 -995 -994]; x1=[1000 3000 5000 6000 4000 2000 500 0 -1000 -3000 -5000 -6000 -4000 -2000 -500 1 999 2999 4999]; y1=[5000 4999 4990 3500 2500 2499 2498 2497 2496 2495 2494 1000 -1000 -999 -998 -997 -996 -995 -994];

Following is the plot I obtained by simply typing in plot(x1,y1):

原始数据图

Is there a way to produce a smooth curve from the above data using the interp1 command? I have been told that I should use cubic splines to achieve the desired plot, however, since I am new to Matlab I am unaware of how to implement such a solution. Thanks in advance!

Edit: I have tried to implement it as follows, but I am getting a hideous looking plot! x1_temp=-6000:100:6000; pc=pchip(x1,y1,x1_temp); plot(x1,y1,'o',x1_temp,pc,'-');

How should I modify this code to produce the right plot?

I think you are confused about what you are interpolating. You should interpolate x1 and y1 separately, and afterwards plot them against each other. The following example produces a smooth curve:

x1=[1000 3000 5000 6000 4000 2000 500 0   -1000 -3000 -5000 -6000 -4000 -2000 -500 1   999 2999 4999];
y1=[5000 4999 4990 3500 2500 2499 2498 2497 2496 2495  2494  1000  -1000 -999 -998 -997 -996 -995 -994];

s = [0,cumsum(sqrt(diff(x1).^2+diff(y1).^2))]
N = length(s);

figure();
plot(x1,y1);
hold on

s_fine = interp1(linspace(0,1,N),s,linspace(0,1,5*N));
pcx=interp1(s,x1,s_fine,'spline');
pcy=interp1(s,y1,s_fine,'spline');
plot(pcx,pcy,'r-');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM