【问题标题】:Numerically compute derivative in MATLAB?在MATLAB中数值计算导数?
【发布时间】:2017-10-17 15:27:10
【问题描述】:

所以我有一个 MATLAB 作业,我们需要使用

计算函数的导数

d f(x)/dx = (f(x0+h) - f(x0-h))/2h

所以我把它做成了一个新函数,并想传入我想要衍生的函数。

我是 MATLAB 的新手,非常感谢您的帮助。这是我得到的,试图计算x = 0.6的导数:

%% Problem 2
syms x;
funct1 = @(x) (x^3)*exp(2*x)
x0     = 0.6;
der1   = FunDer(@funct1,x0);

%% The saved function in a separate file
function [ der ] = FunDer(@funct1,x0)
    % function to calculate derivative
    h   = 1e-5;
    x1  = x0+h;
    x2  = x0-h;
    der = (subs(@funct1,x,x1) - subs(@funct1,x,x2)) / (2*h);
end

【问题讨论】:

  • 在较新的 Matlab 版本中,函数本身不需要放在单独的文件中。

标签: matlab


【解决方案1】:

由于您使用了匿名函数,因此您不需要使用 sym。检查以下修改后的代码:

%% Problem 2
% syms x;
funct1 = @(x) (x^3)*exp(2*x)
x0=0.6;
der1=FunDer(funct1,x0)

%%The saved function in a separate file
function [ der ] = FunDer(funct1,x0)
%function to calculate derivative
h=0.00001;
x1=x0+h;
x2=x0-h;
der = (funct1(x1)-funct1(x2))/(2*h);
end 

【讨论】:

    猜你喜欢
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 2011-08-17
    相关资源
    最近更新 更多