0% found this document useful (0 votes)
14 views1 page

Bisection Method MATLAB Function

This Matlab script uses the bisection method to solve a non-linear equation. It defines an anonymous function F(x), initializes values for the starting interval endpoints a and b, maximum iterations and tolerance. It then iterates, calculating the midpoint xNS and function value FxNS at each step to determine if an exact solution is found or the tolerance is reached, updating the interval accordingly until the solution is obtained or maximum iterations exceeded.

Uploaded by

Andreas Larsson
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views1 page

Bisection Method MATLAB Function

This Matlab script uses the bisection method to solve a non-linear equation. It defines an anonymous function F(x), initializes values for the starting interval endpoints a and b, maximum iterations and tolerance. It then iterates, calculating the midpoint xNS and function value FxNS at each step to determine if an exact solution is found or the tolerance is reached, updating the interval accordingly until the solution is obtained or maximum iterations exceeded.

Uploaded by

Andreas Larsson
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Homework 13

The following is a matlab script file for solving a non-linear equation by the
bisection method. Convert it to a user-defined function

Clear all
F=@ (x) 8-4.5*(x-sin(x)); %defines f(x) as an %anonymous function
a=2; b=3; imax=20; tol = 0.001
%assign initial values to a and b, set max iterations and tolerance
Fa=F(a); Fb=f(b);
if Fa*Fb>0
disp(‘Error: The function has the same sign at points a and b.’)
else
disp(‘iteration a b (xNS) Solutions f(xNS) Tolerance’)
for i=1:imax
xNS=(a+b)/2; % find midpoint between a and b
toli=(b-a)/2; % calculate the current tolerance
FxNS=F(xNS); % calculate the function at the midpoint
fprintf(‘%3i %11.6f %11.6f %11.6f %11.6f %11.6f\n’, I, a, b, xNS,
FxNS, toil)
if FxNS ==0
fprintf(‘An exact solution x=%11.6f was found’,xNS)
break %stop the program if an exact answer is found
end
if toli<tol
break %stop the program if the tolerance is reached
end
if i == imax
fprintf(‘solution was not obtained in %i iterations’,imax)
break %stop the program if the solution is not found
end
if F(a)*FxNS<0
b=xNS
else
a=xNS
end % determine which half the answer lies in and move that
direction
end
end

You might also like