Question

Write a User Defined Function in Matlab solve for the roots of a function using bisection...

Write a User Defined Function in Matlab solve for the roots of a function using bisection method. The user provides two variables for the function to test and bisect if needed.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE

function root= bisection(fun, lb, ub,iter_max, Emax)
flb=fun(lb); % find the f(lb) value
fub=fun(ub); % find the f(ub) value
i=0; % the initial iteration
%Check if you have already found the solution
if flb==0
root=lb;
fprintf('The root is: %5.3f \n', root)
return
end
if fub==0
root=ub;
fprintf('The root is: %5.3f \n', root)
return
end
%now to test if there is a root within the uppper and lower limits
if flb*fub>0
disp('termination type 1: there is no root within bracket')
root=NaN;
return
end
%solution guess
root= (lb+ub)/2;
for i=1:iter_max
rootPrevious=root;
fxr=fun(root);
if i >= iter_max
disp('termination type 0: algorithm terminated due to maximum interations')
break
elseif fxr==0 % test if this is the case where root is directly the root
disp('this is the root')
break
end
% if none of above is met, then process the commands below
if fxr*flb>0
lb=root;
else
ub=root;
end
root= (lb+ub)/2;
error=abs((root-rootPrevious)/root);
if error<Emax
break
end
end
fprintf('The iterations taken is: %d \n', i)
fprintf('The root is: %5.3f \n', root)

Add a comment
Know the answer?
Add Answer to:
Write a User Defined Function in Matlab solve for the roots of a function using bisection...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT