Matlab中对分法程序的错误
我需要编写对分方法的正确实现,这意味着我必须解决所有可能的用户输入错误。这是我的密码:Matlab中对分法程序的错误,matlab,bisection,Matlab,Bisection,我需要编写对分方法的正确实现,这意味着我必须解决所有可能的用户输入错误。这是我的密码: function [x_sol, f_at_x_sol, N_iterations] = bisection(f, xn, xp, eps_f, eps_x) % solving f(x)=0 with bisection method % f is the function handle to the desired function, % xn and xp are
function [x_sol, f_at_x_sol, N_iterations] = bisection(f, xn, xp, eps_f, eps_x)
% solving f(x)=0 with bisection method
% f is the function handle to the desired function,
% xn and xp are borders of search,
% f(xn)<0 and f(xp)>0 required,
% eps_f defines how close f(x) should be to zero,
% eps_x defines uncertainty of solution x
if(f(xp) < 0)
error('xp must be positive')
end;
if(f(xn)>0)
error('xn must be negative')
end;
if (xn >= xp)
error ('xn must be less than xp')
end;
xg=(xp+xn)/2; %initial guess
fg=f(xg); % initial function evaluation
N_iterations=1;
while ( (abs(fg) > eps_f) & (abs(xg-xp) > eps_x) )
if (fg>0)
xp=xg;
else
xn=xg;
end
xg=(xp+xn)/2; %update guess
fg=f(xg); %update function evaluation
N_iterations=N_iterations+1;
end
x_sol=xg; %solution is ready
f_at_x_sol=fg;
if (f_at_x_sol > eps_f)
error('No convergence')
end
函数[x_sol,f_at_x_sol,N_迭代]=二等分(f,xn,xp,eps_f,eps_x)
%用二分法求解f(x)=0
%f是所需函数的函数句柄,
%xn和xp是搜索的边界,
%f(xn)0所需,
%eps_f定义了f(x)与零的接近程度,
%eps_x定义了解x的不确定性
如果(f(xp)<0)
错误('xp必须为正')
结束;
如果(f(xn)>0)
错误('xn必须为负')
结束;
如果(xn>=xp)
错误('xn必须小于xp')
结束;
xg=(xp+xn)/2;%初步猜测
fg=f(xg);%初始功能评估
N_迭代次数=1;
而((abs(fg)>eps_f)和(abs(xg xp)>eps_x))
如果(fg>0)
xp=xg;
其他的
xn=xg;
结束
xg=(xp+xn)/2;%更新猜测
fg=f(xg);%更新功能评估
N_迭代=N_迭代+1;
结束
x_sol=xg;%解决方案准备好了
f_at_x_sol=fg;
if(f_at_x_sol>eps_f)
错误('不收敛')
结束
这是我在Matlab中尝试测试时收到的错误消息:
>> bisection(x.^2, 2, -1, 1e-8, 1e-10)
Attempted to access f(-1); index must be a positive integer or logical.
Error in bisection (line 9)
if(f(xp)<0)
>二等分(x.^2,2,-1,1e-8,1e-10)
试图访问f(-1);索引必须是正整数或逻辑索引。
二等分错误(第9行)
如果(f(xp)如果f是函数句柄,则需要传递函数
bisection(x.^2, 2, -1, 1e-8, 1e-10)
你应该这样做
bisection(@(x)x.^2, 2, -1, 1e-8, 1e-10)
如果f是一个函数句柄,那么您需要传递一个函数
bisection(x.^2, 2, -1, 1e-8, 1e-10)
你应该这样做
bisection(@(x)x.^2, 2, -1, 1e-8, 1e-10)