%%Root Finding Using fzero

% Want to find the roots of a function (points where the function value is
% 0).

% Built in function in MATLAB - fzero(fun, x0)
%fun is a function handle to the function that you want to find the roots
%of
%Can use anonymous functions to make this quick and easy

%x0 is an inital guess of a root (the closer you are, the faster you will
%you get a result).
%x0 can also be a vector of 2 points, which give a range. However, the
%function must have a different sign at each end point

%Usually should try plotting the function to estimate a reasonable x0

%Example: find roots of x^3 - 3x^2 + x/2 + 2cos(x)
xx = -1:.01:3.5;
plot(xx,fctn(xx))

root1 = fzero(@fctn, -0.7);
toBeZero = @fctn;
root2 = fzero(toBeZero, [0.5,1.5]);
root3 = fzero(@(a)fctn(a),3);
root3 = fzero(@(x)x.^3 - 3*x.^2 + x./2 + 2*cos(x),3);


%Can also use this to find where a function is equal to a specific value
%Find where fctn = 4
is4 = fzero(@(a)fctn(a)-4,3);
disp(is4)

