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
We can define a local function to calculate values of and put it at the end of the script.
To calculate the root of the function , 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)
rt = 3.2418
Once you have calculated the root, you can plot and the root of .
Plot for :
x = 0:4; y = f(x); plot(x, y)
Add to the plot the horizontal line , where is the root of .
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 as the local function
f, with an input of
x and an output of
function y = f(x) y = 6*x.^3 - 5*x.^2 -16*x - 100; end