目前我正在对 Secant Method 编写代码,到目前为止代码运行正常。但是,我仍然需要通过计算我在“割线”函数中使用的函数调用次数来更新我的“count.funcCount”。我应该如何修改我的代码?
这是我到目前为止的代码:
function [ root, fcneval, count ] = secant(f, x0, x1, my_options)
my_options = optimset('MaxIter', 50, 'TolFun', 1.0e-5);
count = struct('iterations',0,'funcCount',0,'message',{'empty'});
xp = x0; %# Initialize xp and xc to match with
xc = x1; %# x0 and x1, respectively
MaxIter = 100;
TolFun = 1.0e-5;
%# Secant Method Loop
for i = 2:MaxIter
fd = f(xc) - f(xp); %# Together, the ratio of d and fd yields
d = xc - xp; %# the slope of the secant line going through xc and xp
xn = ((xc * fd) - (f(xc) * d)) / fd; %# Secant Method step
if (abs(xc - xn) < TolFun) && (abs(f(xn)) < TolFun) %# Stopping condition
break;
elseif i > MaxIter %# If still can't find a root after maximum
%# 100 iterations, consider not converge
count.message = sprintf('Do not converge');
end
xp = xc; % Update variables xc and xp
xc = xn;
end
%# Get outputs:
root = xn;
fcneval = f(root);
count.iterations = i;
end %# end function
---------------------------------------
function [f] = fun(x)
f = cos(x) + x;
end
请帮助我,提前谢谢你