Bisection method code matlab

7 views (last 30 days)
Maria Galle
Maria Galle on 11 Oct 2020
Answered: Steven Lord on 12 Oct 2020
I'm trying to write a code using the bisection method to find the root but I'm not sure I wrote it correctly.
t=4;
c_d=0.25; %kg/m
g=9.81;
v=36;
maxit=15;
k = 1;
n_bi(k) = 1; % iteration
x_l_bi(k) = 50; % initial guess lower bound
x_u_bi(k) = 200; % initial guess upper bound
f_xl_bi(k) = sqrt(g*x_l_bi(k)/c_d).*tan(tan(sqrt(g*c_d./x_l_bi(k))*t)) - v;
f_xu_bi(k) = sqrt(g*x_u_bi(k)/c_d).*tan(tan(sqrt(g*c_d./x_u_bi(k))*t))- v;
x_r_bi(k) = (x_l_bi(k) + x_u_bi(k))/2;
product_f_bi(k) = f_xl_bi(k)*x_r_bi(k);
ea_bi(k) = 1*100; % initial error setting in %
while ea_bi(k) > 0.005 & n_bi < maxit
if product_f_bi(k) < 0
x_l_bi(k+1) = x_r_bi(k);
x_u_bi(k+1) = x_u_bi(k);
else
x_l_bi(k+1) = x_l_bi(k);
x_u_bi(k+1) = x_r_bi(k);
end
n_bi(k+1) = k+1;
f_xl_bi(k+1) = sqrt(g*x_l_bi(k+1)/c_d).*tan(tan(sqrt(g*c_d./x_l_bi(k+1))*t))- v;
f_xu_bi(k+1) = sqrt(g*x_u_bi(k+1)/c_d).*tan(tan(sqrt(g*c_d./x_u_bi(k+1))*t))- v;
x_r_bi(k+1) = (x_l_bi(k+1) + x_u_bi(k+1))/2;
product_f_bi(k+1) = f_xl_bi(k+1)*x_r_bi(k+1);
ea_bi(k+1) = abs((x_r_bi(k+1) - x_r_bi(k))/x_r_bi(k+1))*100;
k = k+1;
end
result_bi = [n_bi; x_l_bi; x_u_bi; x_r_bi; ea_bi];
disp([' ']);
disp(['Bisection Method:']);
fprintf('%10s %12s %12s %12s %10s\r\n','iteration','x_l', 'x_u', 'x_r', 'ea');
fprintf('%10.0f %12.4f %12.4f %12.4f %10.2f\n', result_bi);

Answers (1)

Steven Lord
Steven Lord on 12 Oct 2020
Rather than hard-coding the function you want to solve, you might want to create a function handle to the function and use that function handle to evaluate the function. That way you could specify a function from an example in your textbook (I'm assuming this is a homework assignment) and compare the results of your code with the textbook.
n = 3;
f = @(x) x.^n;
% This returns the cubes of the numbers 0 through 4
y = f(0:4)
f = @(x) 2*x+3;
% Now this is two times the numbers 0 through 4 plus 3.
% Same exact evaluation code, different function
y = f(0:4)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!