Ale*_*lex 2 matlab interpolation derivative
假设我有以下数据和命令:
clc;clear;
t = [0:0.1:1];
t_new = [0:0.01:1];
y = [1,2,1,3,2,2,4,5,6,1,0];
p = interp1(t,y,t_new,'spline');
plot(t,y,'o',t_new,p)
Run Code Online (Sandbox Code Playgroud)
您可以看到它们工作得很好,从某种意义上说,插值函数可以很好地匹配节点处的数据点。但我的问题是,我需要计算 y(即 p 函数)wrt 时间的精确导数,并将其与 t 向量作图。怎么做到呢?我不会使用 diff 命令,因为我需要确保导数函数与 t 向量具有相同的长度。非常感谢。
此方法计算多项式的实际导数。如果您有曲线拟合工具箱,您可以使用:
% calculate the polynominal
pp = interp1(t,y,'spline','pp')
% take the first order derivative of it
pp_der=fnder(pp,1);
% evaluate the derivative at points t (or any other points you wish)
slopes=ppval(pp_der,t);
Run Code Online (Sandbox Code Playgroud)
如果您没有曲线拟合工具箱,您可以将fnder线替换为:
% piece-wise polynomial
[breaks,coefs,l,k,d] = unmkpp(pp);
% get its derivative
pp_der = mkpp(breaks,repmat(k-1:-1:1,d*l,1).*coefs(:,1:k-1),d);
Run Code Online (Sandbox Code Playgroud)
资料来源:这个 mathworks 问题。感谢 m7913d 链接它。
附录:
注意
p = interp1(t,y,t_new,'spline');
Run Code Online (Sandbox Code Playgroud)
是捷径
% get the polynomial
pp = interp1(t,y,'spline','pp');
% get the height of the polynomial at query points t_new
p=ppval(pp,t_new);
Run Code Online (Sandbox Code Playgroud)
为了得到导数,我们显然需要多项式,不能只使用新的插值点。为避免两次插入点可能需要很长时间才能处理大量数据,您应该将快捷方式替换为较长的版本。因此,包含您的代码示例的完整工作示例将是:
t = [0:0.1:1];
t_new = [0:0.01:1];
y = [1,2,1,3,2,2,4,5,6,1,0];
% fit a polynomial
pp = interp1(t,y,'spline','pp');
% get the height of the polynomial at query points t_new
p=ppval(pp,t_new);
% plot the new interpolated curve
plot(t,y,'o',t_new,p)
% piece-wise polynomial
[breaks,coefs,l,k,d] = unmkpp(pp);
% get its derivative
pp_der = mkpp(breaks,repmat(k-1:-1:1,d*l,1).*coefs(:,1:k-1),d);
% evaluate the derivative at points t (or any other points you wish)
slopes=ppval(pp_der,t);
Run Code Online (Sandbox Code Playgroud)
一个连续函数的导数是在它的基础上 f(x) 到 f(x+无穷小差) 的差除以所述无穷小差。
在 matlab 中,eps是双精度可能的最小差异。因此,在每个之后t_new我们添加第二个eps更大的点并y为新点进行插值。然后每个点和它的 +eps 对之间的差除以 eps 给出导数。
问题是,如果我们处理如此小的差异,则输出导数的精度会受到严重限制,这意味着它只能具有整数值。因此,我们添加略大于 eps 的值以实现更高的精度。
% how many floating points the derivatives can have
precision = 10;
% add after each t_new a second point with +eps difference
t_eps=[t_new; t_new+eps*precision];
t_eps=t_eps(:).';
% interpolate with those points and get the differences between them
differences = diff(interp1(t,y,t_eps,'spline'));
% delete all differences wich are not between t_new and t_new + eps
differences(2:2:end)=[];
% get the derivatives of each point
slopes = differences./(eps*precision);
Run Code Online (Sandbox Code Playgroud)
如果您想在旧点处获得导数,您当然可以替换t_new为t(或任何其他想要获得其差值的时间)。
在您的情况下,此方法略逊于方法 a),因为它速度较慢且精度较低。但也许它对处于不同情况的其他人有用。