得到数值导数
Get derivative numerically
我有 2 个向量和一个标量:
grid
即 (N x 1);
Value
即 (N x 1);
sval
即 (1,1);
如果我想在 grid
上插入 sval
我知道我可以简单地做:
intervalue = interp1(grid, Value, sval, 'PCHIP');
如果现在我想要导数,即函数 Value
在特定点 sval
的斜率怎么办?
如评论中所述,可以通过forward finite difference近似求导:
slope = diff(Value) ./ diff(grid);
或者:
slope = gradient(Value(1:end-1),grid);
这是numerical differentiation. For a detailed guide on numerical differentiation in MATALB, see this answer的简单方法。
下面是一个具有所需插值的有限差分法示例:
% Define function y = x^3
grid = 1:100;
Value = grid .^ 3;
% Approximate derivative via the local slope
slope = diff(Value) ./ diff(grid);
% Or: slope = gradient(Value(1:end-1),grid);
slope_grid = grid(1:end-1);
% Interpolate derivative
sval = 33.5;
sval_slope = interp1(slope_grid, slope, sval, 'PCHIP');
我们可以将结果可视化:
figure;
plot(grid, 3*grid.^2)
hold on
plot(slope_grid, slope)
legend('Reference', 'Approximation', 'Location', 'NorthWest')
我有 2 个向量和一个标量:
grid
即 (N x 1);Value
即 (N x 1);sval
即 (1,1);
如果我想在 grid
上插入 sval
我知道我可以简单地做:
intervalue = interp1(grid, Value, sval, 'PCHIP');
如果现在我想要导数,即函数 Value
在特定点 sval
的斜率怎么办?
如评论中所述,可以通过forward finite difference近似求导:
slope = diff(Value) ./ diff(grid);
或者:
slope = gradient(Value(1:end-1),grid);
这是numerical differentiation. For a detailed guide on numerical differentiation in MATALB, see this answer的简单方法。
下面是一个具有所需插值的有限差分法示例:
% Define function y = x^3
grid = 1:100;
Value = grid .^ 3;
% Approximate derivative via the local slope
slope = diff(Value) ./ diff(grid);
% Or: slope = gradient(Value(1:end-1),grid);
slope_grid = grid(1:end-1);
% Interpolate derivative
sval = 33.5;
sval_slope = interp1(slope_grid, slope, sval, 'PCHIP');
我们可以将结果可视化:
figure;
plot(grid, 3*grid.^2)
hold on
plot(slope_grid, slope)
legend('Reference', 'Approximation', 'Location', 'NorthWest')