% -----------------------------------------------------
% usingfzero1.m
% -----------------------------------------------------
% Use the fzero function to find the root of the given
% equation (drag coefficient c). 
% This problem is adopted from Chapra and Canale's 
% Numerical Methods for Engineers (Example 5.3).  
% -----------------------------------------------------
% Notes: Interval is estimated using the graphical method. 
% -----------------------------------------------------
% Copyright and license details available at matlabmarina.com
%-------------------------------------------------------

clear;
clc;

% Declare global variables
global mass grav vel time

% Define given parameters
mass = 68.1;     % mass in kg
grav = 9.81;      % acceleration in m/s^2
vel = 40;       % velocity in m/s
time = 10;       % time in s

% Define the upper and lower limits of the interval
% Note that these are estimated by plotting the given equation
coefl = 1;      % drag coefficient in kg/s; lower limit
coefu = 100;    % drag coefficient in kg/s; upper limit
c0 = [coefl, coefu];     % Define the interval for c
% c0 can also be a scalar value (initial estimate of the root)

% Compute the root of f(c)=0 using the fzero function
[c,fval,exitflag,output] = fzero('usingfzero1_Fun',c0);

% c is the root
% fval is the value of the function at c (0 at root)
% exitflag is 1 if root is found successfully
% structure output has information on algorithm used, etc. 

intervaliterations=output.intervaliterations;
iterations=output.iterations;
funcCount=output.funcCount;
algorithm=output.algorithm;
message=output.message;

fprintf('%s\n',message)
fprintf('Number of iterations run: %i\n',iterations)
fprintf('Number of intervals checked: %i\n',intervaliterations)
fprintf('Number of times function evaluated: %i\n',funcCount)
fprintf('Algorithm used: %s\n',algorithm)
fprintf('\n')

if exitflag
    
    fprintf('Root found sucessfully\n')
    fprintf('The root of the function is x = %.4f\n',c)
    fprintf('The value at the root of function is f(x) = %.0f\n',fval)
    
end