matlab - 在没有内置 MATLAB 函数的情况下构造具有自然边界条件的三次样条
问题描述
作为项目的一部分,我必须在不使用任何内置 MATLAB 函数(如 spline 或 csape)的情况下构建具有自然边界条件的三次样条。我尝试编写以下功能。
虽然我很确定它在计算系数 q 时是正确的,但我无法弄清楚我最终将如何得到实际的三次多项式。我现在在调用函数时得到的输出是 S 的 9 个不同值。
任何帮助或提示将不胜感激。
function S=cubic_s(x,y)
n=length(x);
%construction of the tri-diagonal matrix
for j=1:n
V(j,1)=1;
V(j,2)=4;
V(j,3)=1;
end
%the first row should be (1,0,...,0) and the last (0,0,...,0,1)
V(1,2)=1; V(n,2)=1; V(2,3)=0; V(n-1,1)=0;
d=[-1 0 1];
A=spdiags(V,d,n,n);
%construction of the vector b
b=zeros(n,1);
%the first and last elements of b must equal 0
b(1)=0; b(n)=0;
%distance between two consecutive points
h=(x(n)-x(1))/(n-1);
for j=2:n-1
b(j,1)=(6/h^2)*(y(j+1)-2*y(j)+y(j-1));
end
%solving for the coefficients q
q=A\b;
%finding the polynomials with the formula for the cubic spline
for j=1:n-1
for z=x(j):0.01:x(j+1)
S(j)=(q(j)/(6*h))*(x(j+1)-z)^3+(q(j+1)/(6*h))*(z-x(j))^3+(z-x(j))* (y(j+1)/h-(q(j+1)*h)/6)+(x(j+1)-z)*(y(j)/h-(q(j)*h)/6);
end
end
解决方案
function plot_spline
x = (0:10);
y = [1 4 3 7 1 5 2 1 6 2 3];
xx = x(1):0.01:x(2);
[XX,YY]=cubic_s(x,y);
plot(x,y,'*r', XX,YY,'-k')
function [XX,YY]=cubic_s(x,y)
n=length(x);
%construction of the tri-diagonal matrix
for j=1:n
V(j,1)=1;
V(j,2)=4;
V(j,3)=1;
end
%the first row should be (1,0,...,0) and the last (0,0,...,0,1)
V(1,2)=1; V(n,2)=1; V(2,3)=0; V(n-1,1)=0;
d=[-1 0 1];
A=spdiags(V,d,n,n);
%construction of the vector b
b=zeros(n,1);
%the first and last elements of b must equal 0
b(1)=0; b(n)=0;
%distance between two consecutive points
h=(x(n)-x(1))/(n-1);
for j=2:n-1
b(j,1)=(6/h^2)*(y(j+1)-2*y(j)+y(j-1));
end
%solving for the coefficients q
q=A\b;
%finding the polynomials with the formula for the cubic spline
enum = 1;
for j=1:n-1
for z=x(j):0.01:x(j+1)
YY(enum)=(q(j)/(6*h))*(x(j+1)-z)^3+(q(j+1)/(6*h))*(z-x(j))^3+(z-x(j))* (y(j+1)/h-(q(j+1)*h)/6)+(x(j+1)-z)*(y(j)/h-(q(j)*h)/6);
XX(enum)=z;
enum = enum+1;
end
end
推荐阅读
- c++ - 使用 std::istringstream 测试号码失败
- r - 我可以使用随机森林来做特征选择插入符吗
- javascript - 我正在研究数组过滤器。我被困在迄今为止添加过滤器
- azure-devops - 使用“每个”在 Azure DevOps 中构造条件
- python - 如何比较不同数据框熊猫中的两列并用其他列替换值
- css - 背景未显示在网页中
- python - 如何在一定值下遮蔽 seaborn kdeplot?
- lua - Lua string::byte() 在 LuaJit 2.1.0-beta3 中返回 nil
- azure - 使用 azurerm 预配 Terraform 子网时出错
- java - 父子概念中方法同名和变量同名