MATLAB Lesson 9 - More on functions

Estimated time required:

30 minutes

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)

creates an anonymous function called f with an input argument x and which will create an array (vector or matrix) of the same size as the input argument. MATLAB will evaluate the expression f(x) as x .* sin(x), or f(t) as t .* sin(t), or f(3+z) as (3+z) .* sin(3+z), and so on.

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:

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.