以下代码使用 MATLAB 语言,通过 B 样条拟合四组散点数据 (x1, y1), (x2, y2), (x3, y3), (x4, y4),并计算拟合曲线的导数。最终将四条拟合曲线及其导数绘制在同一副图中。

% 输入数据:x1, y1, x2, y2, x3, y3, x4, y4
x = [x1, x2, x3, x4];
y = [y1, y2, y3, y4];

% B样条拟合
p = 3; % B样条次数
knots = [zeros(1,p), linspace(0,1,length(x)-p+1), ones(1,p)]; % 节点向量
coeffs_x = bspline_fit(x, knots, p); % 拟合x坐标
coeffs_y = bspline_fit(y, knots, p); % 拟合y坐标

% 求导
dp = 1; % 求导次数
dx = linspace(0,1,101); % 生成101个点用于绘图
dy_dx1 = bspline_eval(coeffs_x, knots, p, dp, dx); % 第1组数据的导数
dy_dx2 = bspline_eval(coeffs_x, knots, p, dp, dx); % 第2组数据的导数
dy_dx3 = bspline_eval(coeffs_x, knots, p, dp, dx); % 第3组数据的导数
dy_dx4 = bspline_eval(coeffs_x, knots, p, dp, dx); % 第4组数据的导数

% 绘制图形
figure;
plot(x1,y1,'o', x2,y2,'o', x3,y3,'o', x4,y4,'o');
hold on;
plot(bspline_eval(coeffs_x,knots,p,0,dx), bspline_eval(coeffs_y,knots,p,0,dx));
plot(dx, dy_dx1, dx, dy_dx2, dx, dy_dx3, dx, dy_dx4);
legend('Data1', 'Data2', 'Data3', 'Data4', 'B-spline', 'Derivative1', 'Derivative2', 'Derivative3', 'Derivative4');
xlabel('x');
ylabel('y or dy/dx');
title('B-spline Fitting and Derivative');

本代码使用 bspline_fit 函数进行 B 样条拟合,bspline_eval 函数计算导数。最终绘制出原始散点数据、拟合曲线和导数曲线。

请注意,本代码需要您预先定义好 x1, y1, x2, y2, x3, y3, x4, y4 这些变量,分别代表四组散点数据的横坐标和纵坐标。

MATLAB B样条拟合及导数绘制:经过所有散点并画出四条曲线

原文地址: https://www.cveoy.top/t/topic/l1xt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录