割线法:牛顿-拉夫森法的一种变体

时间:2019-09-27 03:19:32

标签: matlab

我必须编写Secant方法的代码:Newton-Raphson方法的一种变体。

我已完成以下操作:

function [SecantMethod] = SecantMethod(x0, x1);

%this is a variation on the Newton-Raphson MEthod, uses two inital guesses
%so that we do not have to explicitly work of the derivative of f(x).

x0 = 2;      
x1 = 1;
%the two guesses

f0 = f(x0);              
f1 = f(x1);
%two coressponding values of the function evaluated at x0 and x1

    x = x1 - (f1*((x1 - x0)/(f1 - f0)));         
    %actual Secant Method (finds x axis intercept between two guesses
end

当我在Matlab中运行代码时,出现错误“未定义的函数或变量'f'”。

我没有要解决的任何特定功能,只需要编写代码即可,所以我不确定该怎么做。

1 个答案:

答案 0 :(得分:1)

您可以让一个函数接受一个函数作为参数,如下所示:

function [SecantMethod] = SecantMethod(f,x0, x1);

disp(f(x0));

end

然后在您的代码中:

%make anonymous function:
f=@(x)(x.^2);
%or:
f=@sin;

%and simply:
SecantMethod(f,1,2)
% or just:
SecantMethod(@myfucntion,1,2)
相关问题