Natural Cubic Spline Interpolation

1 回表示 (過去 30 日間)
BIll_663
BIll_663 2022 年 8 月 13 日
回答済み: Bruno Luong 2022 年 8 月 13 日
Was trying to make a function to do cubic spline interpolation, but kept failing the test file. Anyone can check it out, I appreciate it.
function y=naturalCubicSplinetest1(X,Y)
N=length(X)-1;
P=length(x);
D=diff(Y)./h;
dD3=3*diff(D);
a=Y(1:N);
H=diag(2*(h(2:N)+h(1:N-1)));
for k=1:N-2
H(k,k+1)=h(k+1);
H(k+1,k)=h(k+1);
end
c=zeros(1,N+1);
c(2:N)=H\dD3';
b=D-h.*(c(2:N+1)+2*c(1:N))/3;
d=(c(2:N+1)-c(1:N))./(3*h);
end

回答 (2 件)

Steven Lord
Steven Lord 2022 年 8 月 13 日
Set a breakpoint on the first line of your code. Run your program on an example that you (or your textbook) have worked out, step by step. Identify on which line the results from your program and the manual process diverge, then determine why. Repeat until your code produces the same results as the manually generated solution.
Then repeat this process with other problems (some from your textbook, some from the test suite, some you've made up) until you feel confident you've eliminated all the bugs.

Bruno Luong
Bruno Luong 2022 年 8 月 13 日
You made at least 2 mistakes:
  • h is not computes
  • Typo "x" instead of "X"
The rest of the algorithm I didn't look at carefully but manything seems odd like the for-loop on H.
h = diff(X);
N=length(X)-1;
P=length(X);
D=diff(Y)./h;
dD3=3*diff(D);
a=Y(1:N);
H=diag(2*(h(2:N)+h(1:N-1)));
for k=1:N-2
H(k,k+1)=h(k+1);
H(k+1,k)=h(k+1);
end
c=zeros(1,N+1);
c(2:N)=H\dD3';
b=D-h.*(c(2:N+1)+2*c(1:N))/3;
d=(c(2:N+1)-c(1:N))./(3*h);

カテゴリ

Help Center および File ExchangeSparse Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by