How do you write a code for bisection method and secant method?

8 views (last 30 days)
This is a homework assignment I am having trouble with:
For our bungee jumping problem, write a matlab .M code that solves for the mass given the maximum allowable velocity for a given time. Your MATLAB code must have the following characteristics:
-It solves for mass m using both the bisection and secant methods. Which method is used should be a user‐specified input.
-Other user inputs should be the allowable velocity and the time, and the largest allowable relative error.
-Outputs should be the mass, the number of iterations to find that mass, and the estimated relative error for that mass.
-The loops in the bisection and secant methods should terminate when the estimated relative error is less than the relative error input by the user.
The function is sqrt(g*m/cd)*tanh(t*sqrt(g*cd/m))-v=0, and I'm supposed to solve for the root.
I just started using MATLAB, and the professor does not teach us how to use MATLAB--he gives us an example on EXCEL and then tells us to type a program on MATLAB. If you could give a brief explanation on the more advanced functions that may have to be used, I would appreciate it. This is an example that was given in the textbook, but I am not sure how it is used. I tried to run it on MATLAB and received the message "Error: Function definitions are not permitted in this context."
if true
%function [root,fx,ea,iter]=bisect(func,xl,xu,es,maxit,varargin)
% bisect: root location zeroes
% [root,fx,ea,iter]=bisect(func,xl,xu,es,maxit,p1,p2,...):
% uses bisection method to find the root of func
% input:
% func = name of function
% xl, xu = lower and upper guesses
% es = desired relative error (default = 0.0001%)
% maxit = maximum allowable iterations (default = 50)
% p1,p2,... = additional parameters used by func
% output:
% root = real root
% fx = function value at root
% ea = approximate relative error (%)
% iter = number of iterations
if nargin<3,error('at least 3 input arguments required'),end
test = func(xl,varargin{:})*func(xu,varargin{:});
if test>0,error('no sign change'),end
if nargin<4|isempty(es), es=0.0001;end
if nargin<5|isempty(maxit), maxit=50;end
iter = 0; xr = xl; ea = 100;
while (1)
xrold = xr;
xr = (xl + xu)/2;
iter = iter + 1;
if xr ~= 0,ea = abs((xr - xrold)/xr) * 100;end
test = func(xl,varargin{:})*func(xr,varargin{:});
if test < 0
xu = xr;
elseif test > 0
xl = xr;
else
ea = 0;
end
if ea <= es | iter >= maxit,break,end
end
root = xr; fx = func(xr, varargin{:});
code
end
  1 Comment
Image Analyst
Image Analyst on 26 Jan 2015
How did you call it? Did you supply it with any arguments? Or you just clicked the green "Run" triangle and hoped for the best? By the way, it should use | | instead of |.

Sign in to comment.

Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!