MATLAB中割线寻根函数的几个问题

MATLAB中割线寻根函数的几个问题,matlab,Matlab,我已经在这个函数上乱搞了一段时间了,我似乎找不到解决这个问题的方法 我的代码是: function [x,i] = secant(f, x0, x1, tol, maxiters) %SECANT Secant method % [X,I] = SECANT(F, X0, X1, TOL, MAXITERS) performs the secant % method with F(x), starting at x_0 = X0 and x_1 = X1, and continuing % un

我已经在这个函数上乱搞了一段时间了,我似乎找不到解决这个问题的方法

我的代码是:

function [x,i] = secant(f, x0, x1, tol, maxiters)
%SECANT Secant method
% [X,I] = SECANT(F, X0, X1, TOL, MAXITERS) performs the secant
% method with F(x), starting at x_0 = X0 and x_1 = X1, and continuing
% until either |X_i+1 - X_i| <= TOL, or MAXITERS iterations have
% been taken. The number of iterations, I, is also returned.
% An error is raised if the first input is not a function handle.
% A warning is raised if the maximum number of iterations is reached
% without achieving the tolerance.

if ~isa(f, 'function_handle')
error('Your first input was not a function handle')
end

i = 0; % initialise iterate counter
x = x1;
x_old = x0; 
while abs(x - x_old) > tol && i < maxiters
x_old = x0;
x = x - f(x)*(x - x_old)/(f(x) - f(x_old)); % compute the new x
i = i + 1; % increase our counter by one

end
if abs(x - x_old) > tol
warning('Maximum number of iterations reached without achieving tolerance.')
end
我相信我的问题来自于行
x_old=x0
位于
下方,而abs(x-x_old)>tol&i
。我想每次调用该函数时,它都会将
x
设置回
x0


我怎样才能避开这个问题呢?

问题就如你所说。x_old始终设置为0,而事实上,每次迭代i都应将其设置为x_i-2。这是您需要更改的相关代码

i = 0; % initialise iterate counter
%Store the initial values in a different variable
x_0 = x0;
x_1 = x1;
while abs(x - x_old) > tol && i < maxiters
    x = x_1 - f(x_1) * (x_1 - x_0)/(f(x_1) - f(x_0)); % compute the new x
    % Update the previous values
    x_0 = x_1;
    x_1 = x;
    i = i + 1; % increase our counter by one
end
i=0;%初始化迭代计数器
%将初始值存储在不同的变量中
x_0=x0;
x_1=x1;
而abs(x-x_old)>tol&i
i = 0; % initialise iterate counter
%Store the initial values in a different variable
x_0 = x0;
x_1 = x1;
while abs(x - x_old) > tol && i < maxiters
    x = x_1 - f(x_1) * (x_1 - x_0)/(f(x_1) - f(x_0)); % compute the new x
    % Update the previous values
    x_0 = x_1;
    x_1 = x;
    i = i + 1; % increase our counter by one
end