2 | Custom Functions
In this section, we make our own custom functions as m files and as inline functions. We then use our custom functions in two MATLAB functions: fzero and fminsearch. Finally, we look at using options within some of MATLAB’s functions.
At the end of this section you should be able to:
Identify points on a plot using the data cursor or ginput
Create and save function files as m files
Create inline functions
Pass multiple scalar and vector arguments into functions
Receive multiple scalar and vector outputs from functions
Use fminsearch to find maxima and minima of functions
Use fzero to find zeros or arbitrary values of a function
Creating Custom Functions
Recent versions of MATLAB allow you to create functions in three ways: as a stand-alone m file, as an inline (or anonymous or lambda) function, and now as a function defined at the bottom of a script file. We will not cover the third (newer) method in this course.
Functions as m Files
Custom Functions: create m files with input(s) and output(s) that we can call from the command line, scripts or other functions. In this example, we make a function that converts the temperature in Celsius to Fahrenheit and Kelvin.
Example 1: using an m file to make a function calculate the height of a ball thrown into the air.
Live Example 1: Creating a function to calculate radioactive decay and using the function to create a plot
Live Example 2: Converting decimal degrees (DD) to degrees-minutes-seconds (DMS) and back using vector inputs and output.
Functions as In-Line (Anonymous) Functions
Inline Functions: assign functions to variables rather than making a separate m file. Inline functions are useful for simple functions that are only one line and have one output. These are also known as lambda functions in other programming languages (e.g., Python).
Example 2: using an inline function in Matlab to create and plot y = (t+a)cos(t+b).
Functions of Functions
fzero
Using fzero: use the fzero function to find a zero of a function (m file or inline). You need to assign an initial “guess” to where the zero is which will determine which zero you find. The function works only on single variable functions. This example uses the function from the previous example.
fminsearch
Using fminsearch: the basics of employing fminsearch to find the minimum (or maximum) of a function without needing its derivative. You need to supply an initial guess(es) to where the max/min is located. Depending on your guess you will find a local or global min/max. fminsearch works on functions of several variables but you must use them in vector form.
fminsearch Example: Using fminsearch for minimizing a function of several variables. In this example we find the and that minimizes f(x,y)=4x^2+6(y^2-1)+4xy. We create a matrix output using meshgrid and visualize the 3D plot using meshc.