Recap
In previous lessons you learnt how to define simple anonymous functions. Anonymous functions can be used with several variables and parameters, but only in the workspace in which they are defined.Functions
The ability to define functions to simplify the task of repeatedly doing a set of calculations with different inputs is essential for many tasks, including solving a nonlinear equation, integrating or differentiating a function, or defining a differential equation.
Anonymous functions
We have seen how to create a simple anonymous function in MATLAB using the @ character. For instance, the following statement
f = @(x) x .* sin(x)
Function M-files
However, this method of defining a function is not suitable when the definition of the function is more complicated, or you want to use the function in a variety of different contexts. Then function M-files are used. These are just M-files (plain text files with a .m extension) with a special header line at the beginning.Objectives
The aim of this module is to understand more on how to define functions in MATLAB.
What you should know by the end of this module:
- How to create anonymous functions with several input arguments and parameters;
- How to creat a function M-file, with multiple input and output arguments;
- How to document a function M-file;
- The difference between MATLAB's workspace and local workspaces for functions.
Instructions
Work your way through the pages of this lesson using the links in the blue bar above or at the bottom of each page. You should do them in order initially but you can return to any of them when you need to refresh your memory. You can print the pages by using the printable copy icon in the Resources menu bar to the right.
Hint: Have these lessons open in a web browser and MATLAB open in another window so you can try all the examples as you work through the lessons.
It is recommended that you attempt the self-test exercises that you will find on each page.
There is a quiz at the end of the module for which you will receive a grade.
You final mark for this quiz will be the highest mark you achieve before the due date for the quiz.