%% Add Functions to Scripts
% MATLAB® scripts, including live scripts, can contain code to define functions. These functions are called local functions.
% Local functions are useful when you are working with functions that require function handles as inputs. For example, suppose you want to find the root of the function
% f\left(x\right)={6x}^3 -5x^2 \;-\;16x-100
% We can define a local function to calculate values of f\left(x\right) and put it at the end of the script.
% To calculate the root of the function f\left(x\right), use the fzero function. Call fzero using the function handle f and an initial starting value of 2.

x0 = 2; % initial value
rt = fzero(@f, x0)

%
% Once you have calculated the root, you can plot f\left(x\right) and the root of f\left(x\right).
% Plot y=f\left(x\right) for 0\le x\le 4:

x = 0:4;
y = f(x);
plot(x, y)

%  Add to the plot the horizontal line x=\textrm{rt}, where \textrm{rt} is the root of f\left(x\right).

hold on
plot([rt,rt], [-150, 150]) 

%
% All local function definitions must be placed at the end of the file, after the script code. Here is the definition of the function f\left(x\right)={6x}^3 -5x^2 \;-\;16x-100 as the local function f, with an input of x and an output of y.

function y = f(x)
    y = 6*x.^3 - 5*x.^2 -16*x - 100;
end

% Copyright 2012 The MathWorks, Inc.