MATLAB Guide

Chapter 10: More on Functions

10.1 Passing a Function as an Argument

Common to many problems tackled with MATLAB is the need to pass a function as an argument to another function. This can be done in several ways, depending on how the function being called has been written. We illustrate using ezplot, which plots a function f(x) over a default range of [ ?2 ?,2 ?]. First, the function can be passed via a function handle. A function handle is a MATLAB datatype that contains all the information necessary to evaluate a function. A function handle can be created by putting the @ character before the function name. Thus if fun is a function M-file of the form required by ezplot then we can write

  ezplot (@fun)

As well as being an M-file, fun can be the name of a built-in function:

  ezplot (@sin)

The name of a function can also be passed as a string:

  ezplot ('exp')

Function handles are new to MATLAB 6 and are preferred to the use of strings, as they are more efficient and more versatile. However, you may occasionally come across a function that accepts a function argument in the form of a string but will not accept a function handle. You can convert between function handles and strings using func2str and str2func. For help on function handles type help function_handle.

There are two further ways to pass a function to ezplot

UNLIMITED FREE
ACCESS
TO THE WORLD'S BEST IDEAS

SUBMIT
Already a GlobalSpec user? Log in.

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.

Customize Your GlobalSpec Experience

Category: Handles and Pulls (industrial)
Finish!
Privacy Policy

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.