没有办法以代数方式获取 m 文件中定义的函数句柄或函数的导数。您必须通过在多个点上评估函数并逼近导数来以数值方式执行此操作。
你可能想要做的是符号方程的微分,你需要符号数学工具箱。这是使用Newton-Raphson 方法查找根的示例:
>> syms x %# Create a symbolic variable x
>> f = (x-4)^2-4; %# Create a function of x to find a root of
>> xRoot = 1; %# Initial guess for the root
>> g = x-f/diff(f); %# Create a Newton-Raphson approximation function
>> xRoot = subs(g,'x',xRoot) %# Evaluate the function at the initial guess
xRoot =
1.8333
>> xRoot = subs(g,'x',xRoot) %# Evaluate the function at the refined guess
xRoot =
1.9936
>> xRoot = subs(g,'x',xRoot) %# Evaluate the function at the refined guess
xRoot =
2.0000
您可以看到,xRoot
经过几次迭代后, 的值就接近于真正根的值(即 2)。您还可以将函数评估放在 while 循环中,条件是检查每个新猜测和前一个猜测之间的差异有多大,当差异足够小时(即已找到根)时停止:
xRoot = 1; %# Initial guess
xNew = subs(g,'x',xRoot); %# Refined guess
while abs(xNew-xRoot) > 1e-10 %# Loop while they differ by more than 1e-10
xRoot = xNew; %# Update the old guess
xNew = subs(g,'x',xRoot); %# Update the new guess
end
xRoot = xNew; %# Update the final value for the root