﻿ Expanding MATLAB’s Power with Functions - MATLAB For Dummies, 2nd Edition

Chapter 9

# Expanding MATLAB’s Power with Functions

IN THIS CHAPTER

Finding and using built-in functions

Defining and using your own functions

Understanding other function types

Simplification is an important part of creating any useful application. The better you can outline what tasks the application performs in the simplest of terms, the easier it is to define how to interact with and expand the application. Understanding how an application works is the reason you use functions. A function is simply a kind of box in which you put code. The function accepts certain inputs and provides outputs that reflect the input received. It isn’t important to understand precisely how the function performs its task unless your task is to modify that function, but being able to visualize what task the function performs helps you understand the application as a whole. The only requirement is that you understand the inputs and resulting outputs. In short, functions simplify the coding experience.

This chapter is about three sorts of functions. If you’ve followed along in previous chapters, you have already used quite a few built-in functions, but simply using them may not be enough. You need to understand a little more about the inputs and outputs — the essentials of how the box works. On the other hand, you don’t find out about the inner mechanisms of built-in functions in this chapter because you never need to know about those aspects.

You also get a chance to create your own functions in this chapter. The examples in previous chapters have been easy, so the need to provide simplification just isn’t there. As the book progresses, you create more complex examples, so the need to simplify the code used in those examples becomes more important. Creating your own functions will make both the examples and your own code easier to understand.

MATLAB also supports some interesting alternatives to functions. They aren’t functions in the traditional sense, but they make working with code simpler. These “special purpose” functions are used when the need arises to create code that is both efficient and elegant. The final part of this chapter provides a good overview of these special function types, and you see them used later in the book.

You don’t have to type the source code for this chapter manually. In fact, using the downloadable source is a lot easier. You can find the source for this chapter in the \MATLAB2\Chapter09 folder of the downloadable source. When using the downloadable source, you may not be able to work through some of the hands on examples because the example files will already exist on your system. In this case, you can create an alternative folder, Chapter09a, to hold the results of the hands on exercises. (See the Introduction for details on how to obtain the downloadable source.)

Working with Built-in Functions

Built-in functions are those that come with MATLAB or are part of an add-on product. You typically don’t have source code for built-in functions and must treat them simply as black boxes. So far, you have relied exclusively on built-in functions to perform tasks in MATLAB. For example, when you use the input() and disp() functions in Chapter 8, you’re using built-in functions. The following sections tell you more about built-in functions and how you can work with them in MATLAB to achieve specific objectives.

There are many functions you can use to learn about built-in functions:

· help()

· doc()

· docsearch()

· lookfor()

· what()

If you already know the name of a function, one of the simplest makes use of the help('function_name') command, where function_name is the name of the function. Try it now. Type help('input') and press Enter in the Command Window. You see output similar to the output shown in Figure 9-1.

FIGURE 9-1: Obtain help directly from MATLAB for built-in functions you know.

MATLAB does provide some types of category help. For example, type help('elfun') and press Enter to see a listing of elementary math functions at your disposal. When you type help('specfun') and press Enter, you see a listing of specialized math functions.

Sometimes the help information provided by the help() function becomes excessively long. In this case, you can use the more() function to present the information a page at a time. Before you use the help() function, type more('on') and press Enter to put MATLAB in paged mode. When the help information is more than a page in length, you see a

--more--

prompt at the bottom of the screen. Press the spacebar to see the next page or type q to end the output. If you want to see only the next line, press Enter instead. When you finish reviewing help, type more('off') and press Enter to turn off paged mode.

Although the help() function is really useful because it displays the information you need directly in the Command Window, sometimes the doc() function is a better choice. When using the doc() function, you see a nicely formatted output that includes links to example code and other information. Type doc('input') and press Enter, and you see the output shown in Figure 9-2. This is the option you should use when you want to get an in-depth view of a function rather than simply jog your memory as part of writing an application. In addition, when you find that the help() function is less helpful than you’d like, the doc() function generally provides more information.

FIGURE 9-2: Use the doc() function when you need in-depth information about a built-in function.

Using help() may not always be possible because you don’t know the precise name of whatever you need to find. Another useful function is docsearch(). You use this function when you have some idea, but not a precise one, of what you need to find. For example, type docsearch('input') and press Enter in the Command Window. This time you see a list of potential entries to query, as shown in Figure 9-3. Notice that the input() function is still the first entry in the list, but you have a number of other choices as well.

FIGURE 9-3: Search for what you need within the documentation.

One of the more interesting ways to search for built-in functions is to use the lookfor() function. In this case, MATLAB doesn’t look in the documentation; rather, it looks in the source code files. This kind of search is important because you can sometimes see connections between functions this way and find alternatives that might not normally occur to you. To see how this kind of search works, type lookfor('input') and press Enter. You see the output shown in Figure 9-4. Notice that the input() function is in the list, but it doesn’t appear at the top because the search doesn’t sort the output by likely candidate.

If you really want to know more about the built-in functions from a coding perspective, start with the which() function, which tells you the location of the built-in function. For example, type which('input') and press Enter. You see the location of this built-in function on your system. On my system, I receive this output: built-in (C:\Program Files\MATLAB\R2020b\toolbox\matlab\lang\input).

At this point, you know that input() is found in the lang folder. However, you really don’t know what related functions might be in the same folder. Use the what() function to locate additional information about the content of the lang folder. To see this for yourself, type what('lang') and press Enter. You see a relatively long listing of function names like this:

MATLAB Code files in folder

C:\Program Files\MATLAB\R2020b\toolbox\matlab\lang

Contents evalin munlock

ParallelException exist nargchk

ans feval nargin

FIGURE 9-4: In some cases, you need to look for associations as part of your search.

Notice that the output includes the disp() function that you used with the input() function in Chapter 8. However, you also see a number of other interesting functions in the list that could prove useful. If this listing still doesn’t quench your need for more information about functions, check out the complete function list at https://www.mathworks.com/help/matlab/referencelist.html.

Not shown in the previous output is a listing of classes and packages found in the lang folder. Classes and packages are simply two other ways of packaging functionality within MATLAB. However, these two packaging methods provide more functionality than functions do in most cases, so it pays to look them up to see what sorts of things you can do with them. Using the doc() and help() functions provides you with information about the classes and packages.

Sending data in and getting data out

The essence of a function is that it presents you with a black box. In most cases, you send data in, it whirls around a bit, and then data comes back out. Managing data is an essential part of most functions.

Of course, some functions require only input, some provide only output, and some perform tasks other than work directly with data. For example, the clc() function clears the Command Window and doesn’t require any data input or produce any data output to perform the task. Every function does something; creating one that does nothing would be pointless.

The problem for many people is determining the input and output requirements for the built-in functions. The best way to discover this information is to use the help() or doc() functions. The doc() function is actually the easiest to use in this case. The input and output arguments appear at the bottom of the help screen. To see this for yourself, type doc('input') and press Enter. Scroll down to the bottom of the resulting page (refer to Figure 9-2) and you see the inputs and outputs.

In this case, you see that the input argument is a prompt and that you must provide this input as a string. The documentation explains that the prompt is there to ask the user for a specific kind of input. The output can take two forms: an array that is calculated from the input or a string that contains the precise text the user has typed.

When you see a dual output for a function, it means that you need to tell the function what sort of output to provide or that there is a default. In this case, the input() function requires that you supply a second argument, 's', to obtain the string output. The default is to provide the calculated array.

Creating a Function

Functions represent another method for packaging your code (but not the last discussed in the book; you also see classes discussed in Chapter 13). They work as an addition to scripts rather than a replacement for them. Scripts and functions each have a particular place to occupy in your MATLAB toolbox. The first section that follows explains these differences and helps you understand when you would use a script or a function. In some cases, it doesn’t matter too much, but in other cases, the wrong choice can cause you a lot of frustration and wasted time.

The remainder of the sections that follow help you create custom functions of various types. You start with a simple function that doesn’t require any input or output to perform a task. After that, you start to build functions with greater complexity that are also more flexible because they do accept input and produce output. Functions can be as simple or as complex as needed to perform a task, but simpler is always better (an emphasis of this chapter as a whole).

Understanding script and function differences

A script is a method of packaging a procedure — in other words, a series of steps that you use to perform a task. Some people have compared scripts to keyboard macros or other forms of simple step recording. On the other hand, a function is a method of packaging a transformation — code that is used to manage data in some manner or to perform a task that requires better data handling than a script can provide. Both types of packages contain code of a sort, but each packaging method is used differently. (Live Scripts, discussed in Chapter 11, and Live Functions, discussed in Chapter 12, are simply different ways to interact with scripts and functions.)

Scripts and functions also handle data differently. A script makes all the variables that it contains part of the workspace. As a result, after the script runs, you can easily see all the variables that the script contains as well as their ending values. A function hides its variables, and the variables become unavailable after the function runs. As a result, the actual data that the function uses internally isn’t visible, and you must supply any required inputs every time you run the function.

As you see later in this section, a function also has a special header that identifies the function name, the inputs that it requires, and the outputs it provides. A function is a formal sort of coding method that’s more familiar to developers. However, functions also provide greater flexibility because you can control the environment in which they perform tasks with greater ease.

The use of inputs and outputs reduces the potential for contamination by data left over from a previous run and, like Las Vegas, what happens in the function stays in the function. This feature is a big advantage: You can use the same name in a function as you would outside it without interference, and doing so avoids a lot of confusion.

Both scripts and functions reside in files that have an .m extension. The immediately noticeable difference between the two is that a script lacks a header. Functions always have the header that you see in the “Writing your first function” section, coming up shortly.

Understanding built-in function and custom function differences

Built-in functions (those provided with MATLAB) and custom functions (those you create yourself or that come as part of a third-party product) differ in at least one important aspect. The custom functions come with source code. You can modify this source code as needed to meet your particular needs.

The built-in input() function comes with MATLAB, and you can find it in the input.m file in the toolbox\matlab\lang directory used to contain part of the files for your MATLAB installation. However, if you open that file, you see documentation but no source code. The source code is truly part of MATLAB, and you can’t edit it. You can modify the documentation as necessary with your own notes, but this really isn’t a recommended procedure because the next MATLAB update will almost certainly overwrite your changes.

Creating a function is only slightly more work than creating a script. In fact, the two processes use the same editor, so you’re already familiar with what the editor can provide in the way of help. The various Editor features you’d use for creating a script all work the same way with functions, too. (You have access to the same double percent sign (%%) for use with sections, for example.) The following steps get you started creating your first function. You can also find this function in the SayHello.m file supplied with the downloadable source code.

1. Click the arrow under the New entry on the Home tab of the MATLAB menu and select Function from the list that appears.

You see the Editor window, shown in Figure 9-5. Notice that the editor already has a function header in place for you, along with the inputs, outputs, and documentation comments.

FIGURE 9-5: The Editor window helps you create new functions.

Figure 9-5 may look a little complex, but that’s because MATLAB includes a number of optional elements that you will see in action later in the chapter. A function has three requirements:

· A function always begins with the word function.

· You must include a function name.

· A function must always end with the keyword end.

2. Delete outputArg1,outputArg2, but not the square brackets.

Functions aren’t required to have output arguments. In order to keep things simple for your first function, you’re not going to require any inputs or outputs.

An argument is simply a word for an individual data element. If you supply a number to a function, the number is considered an argument. Likewise, when you supply a string, the entire string is considered just one argument. A vector, even though it contains multiple numbers, is considered a single argument. Any single scalar or object that you provide as input or that is output from the function is considered an argument.

3. Delete inputArg1,inputArg2, but not the parentheses.

Functions aren’t required to have input arguments.

4. Change the function name from untitled toSayHello.

Your function should have a unique name that reflects its purpose. Avoiding existing function names is essential. Before you name your function, test the name you’re considering by typing help('NameOfYourFunction') and pressing Enter. If the function already exists, you see a help screen. Otherwise, MATLAB denies all knowledge of the function, and you can use the function name you have chosen.

Always provide help information with the functions you create. Otherwise, the help() function won’t display any help information, and someone could think that your function doesn’t exist. If you want to be certain that there is no potential conflict between a function you want to create and an existing function (even a poorly designed one), use the exist() function instead, such as exist('SayHello'). When the function exists, you see an output value of 2 (which is the value for a function with a .m, .mlx, or .mlapp extension; built-in functions will output a value of 5). Otherwise, you see an output value of 0.

%SayHello()

% This function says Hello to everyone!

Notice that the second line is indented. The indentation tells MATLAB that the first line is a title and the second is text that goes with the title. Formatting your comments becomes important when working with functions. Otherwise, you won’t see the proper help information when you request it.

6. Delete the existing code before the end statement; then add the following code after the comment:

disp('Hello There!');

The function simply displays a message onscreen.

7. Click Save on the Editor tab.

You see the Select File for Save As dialog box.

8. Select the Chapter09 directory for the source code for this book, typeSayHello.m in the File Name field, and then click Save.

MATLAB saves your function as SayHello.m.

The filename you use to store your function must match the name of the function. MATLAB uses the filename to access the function, not the function name that appears in the file. When there is a mismatch between the function name and the filename, MATLAB displays an error message.

Using the new function

You have a shiny new function and you’re just itching to use it. Before you can use the function, you must make sure that the directory containing the function file is part of the MATLAB path. You can achieve this goal in two ways:

· Double-click the directory entry in the Current Folder window.

· Right-click the directory entry in the Current Folder window and choose Add to Path ⇒ Selected Folders and Subfolders from the context menu.

You can try your new function in a number of ways. The following list contains the most common methods:

· Click Run in the Editor window, and you see the output in the Command Window. However, there is a little twist with functions that you discover in the upcoming “Passing data in” section of the chapter. You can’t always click Run and get a successful outcome, even though the function will always run.

· Click Run and Advance in the Editor window. (This option runs the selected section when you have sections defined in your file.)

· Click Run and Time in the Editor window. (This option outputs profiling information — statistics about how the function performs — for the function.)

· Type the function name in the Command Window and press Enter.

Your function also has help available with it. Type help('SayHello') and press Enter. MATLAB displays the following help information:

SayHello()

This function says Hello to everyone!

The output is precisely the same as it appears in the function file. The doc() function also works. Type doc('SayHello') and press Enter. You see the output shown in Figure 9-6. Notice how the title is presented in a different color and font than the text that follows. In addition, clicking the View Code for SayHello link displays the function’s source code.

FIGURE 9-6: The help you provide is available to anyone who needs it.

Passing data in

The SayHello() function is a little limited. For one thing, it can’t greet anyone personally. To make SayHello() a little more flexible, you need to pass some information to it in the form of an input argument. The following steps help you create an updated SayHello() that accepts input arguments. You can also find this function in the SayHello2.m file supplied with the downloadable source code.

1. Click the down arrow under the Save option on the Editor tab of the Editor window and choose Save As.

You see the Select File for Save As dialog box.

2. Type SayHello2.m in the File Name field and click Save.

MATLAB saves the function that you created earlier using a new name. Notice that the function name is now highlighted in orange. The highlight tells you that the function name no longer matches the filename.

3. Change the function name from SayHello toSayHello2.

The orange highlight disappears when you place the text cursor in another location in the Editor window.

4. Add the input argument Name to the function header so that the header looks like this:

function [ ] = SayHello2( Name )

Notice that Name is now highlighted in orange to show that you haven’t used it anywhere. The highlight will go away after you make the next change. The Editor window always displays an orange highlight when it detects a problem with your code. It’s important to realize that the Code Analyzer feature of MATLAB detects only potential errors. (You can read more about the Code Analyzer at https://www.mathworks.com/help/matlab/matlab_prog/matlab-code-analyzer-report.html.) It can’t absolutely tell you that a problem exists, so you need to look carefully at the highlights.

5. Change the disp() function call so that it looks like this:

disp(['Hello There ', Name, '!']);

The disp() function now requires use of the concatenation operator that was introduced in Chapter 8 to combine the text with the input argument. The output will contain a more personalized message.

6. Click Run.

MATLAB displays a message telling you that the SayHello2() function requires input, as shown in Figure 9-7. You see this message every time you try to use Run to start the function because functions don’t store argument information as scripts do.

FIGURE 9-7: MATLAB knows to ask you for the input arguments as needed.

7. Type 'Ann' in the Run drop-down and press Enter.

You see the expected output of:

Hello There Ann!

The Run button will remember what you used for input the next time you click it. Here is how you can interact with the button’s memory:

· To clear this value, click the down arrow under the Run button, right-click the Run command, and then choose Delete from the context menu that appears.

· To modify this value, click the down arrow under the Run button, right click the Run command, and then choose Edit from the context menu that appears. You will then be able to edit the existing value by typing a new value.

8. Type SayHello2('Josh') in the Command Window and press Enter.

You see the expected output.

As you modify your functions, you should also modify the comments for them. Because you add Name as an input argument, you should document it in the comments for this function, as shown in the following in bold:

%SayHello2()

% This function says Hello to everyone!

% It requires a string, Name, as input.

Adding this comment will also change the output of functions like help() and doc() so that people know why SayHello2() is different from SayHello(). If you don’t take this extra step, other people could use the wrong function for a particular need.

Passing data out

When functions manipulate data, they pass the result back to the caller. The caller is the code that called the function. The following steps help you create an updated SayHello2() function that passes back the string it creates. You can also find this function in the SayHello3.m file supplied with the downloadable source code.

1. Click the down arrow under the Save option on the Editor tab of the Editor window and choose Save As.

You see the Select File for Save As dialog box.

2. Type SayHello3.m in the File Name field and click Save.

MATLAB saves the function you created earlier using a new name.

3. Change the function name from SayHello2 toSayHello3.

The orange highlight disappears when you place the text cursor in another location in the Editor window.

4. Type HelloString in the square brackets before the function name so that your function header looks like this:

function [ HelloString ] = SayHello3( Name )

The function now returns a value to the caller. You see the orange highlight again because SayHello3() doesn’t assign a value to HelloString yet.

5. Modify the function code to include an assignment to HelloString, like this:

HelloString = ['Hello There ', Name, '!'];

disp(HelloString);

The function now assigns a value to HelloString and then uses that value as output. It also returns the output to the caller.

6. Save the changes you’ve made.

7. Type Output = SayHello3('Ambrose') in the Command Window and press Enter.

You see the following output:

Hello There Ambrose!

Output =

'Hello There Ambrose!'

8. Type disp(Output) in the Command Window and press Enter.

You see the expected greeting as output.

Creating and using global variables

Functions normally use local variables — that is, they aren’t visible to anyone but the function. Using local variables avoids confusion because each function is self-contained. In addition, using local variables makes functions more secure and reliable because only the function can access the data in the variable.

USING OPTIONAL ARGUMENTS

Dealing with optional arguments requires some MATLAB features that are covered in later chapters, so you can feel free to skip this sidebar for now and come back to it later. The current version of the SayHello2() function requires an argument. You must supply a name or the function won’t run. A number of functions that you have already used, such as disp(), provide optional arguments — you can choose to use them or not. Optional arguments are important because there are times when a default argument works just fine. In fact, you can change SayHello2() so that it doesn’t require an argument.

To make SayHello2() work without an input argument, you must assign a value to Name, but only if Name doesn’t already have a value. In order to make the assignment, you first need to determine whether Name does have a value by checking a variable that MATLAB provides for what you called nargin (for Number of Arguments Input). If nargin equals 1, then the caller — the code that called this function — has provided an input. Otherwise, you need to supply the input to Name. Here’s the updated version of SayHello2() that you can find in the downloadable source as SayHello2a.m.

function [ ] = SayHello2a( Name )

%SayHello2a()

% This function says Hello to everyone!

% It allows an optional a string, Name, as input;

% Name has a default value of 'Good Looking'.

if nargin < 1

Name = 'Good Looking';

end

disp(['Hello There ', Name, '!']);

end

The additional code states that if nargin is less than 1, the function needs to assign it a value of 'Good Looking'. Otherwise, the function uses the name provided by the caller. To test this code, type SayHello2a and press Enter in the Command Window. You see Hello There Good Looking! as output. Of course, the function could be broken, so type SayHello2a('Selma') and press Enter. You see Hello There Selma! as output, so the function works precisely as it should, and Name is now an optional argument.

You may find that you need to make a variable visible, either because it is used by a number of functions or the caller needs to know the value of the variable. When a function makes a local variable visible to everyone, it becomes a global variable. Global variables can be misused because they’re common to every function that wants to access them and they can present security issues because the data becomes public.

The following steps show how to create a global variable using SayHello3 as a starting point. You can also find these functions in the SayHello4.m and SayHello5.m files supplied with the downloadable source code.

1. Click the down arrow under the Save option on the Editor tab of the Editor window and choose Save As.

You see the Select File for Save As dialog box.

2. Type SayHello4.m in the File Name field and click Save.

MATLAB saves the function you created earlier using a new name.

3. Change the function name from SayHello3 toSayHello4.

The orange highlight disappears when you place the text cursor in another location in the Editor window.

4. Remove HelloString from the square brackets before the function name so that your function header looks like this:

function [ ] = SayHello4( Name )

When a variable is global, you can’t return it as data from a function call. The data is already available globally, so there is no point in returning it from the function.

5. Change the HelloString assignment so that it now contains the global keyword, as shown here:

global HelloString;

HelloString = ['Hello There ', Name, '!'];

6. Save the changes you’ve made.

7. Type SayHello4('George') in the Command Window and press Enter.

You see the following output:

Hello There George!

At this point, there is a global variable named HelloString sitting in memory. Unfortunately you can’t see it, so you don’t really know that it exists for certain.

8. Perform Steps 1 through 3 again to create SayHello5().

9. Modify the SayHello5() code so that it looks like this:

function [ ] = SayHello5( )

%SayHello5()

% This function says Hello to everyone using

% a global variable!

% It requires a string, Name, as input.

% HelloString is now a global variable.

global HelloString

disp(HelloString);

end

Notice that SayHello5() doesn’t accept input or provide output arguments. In addition, it only declares HelloString; it doesn’t actually assign a value to it, so the function should fail when it calls the disp() function.

10. Type SayHello5 in the Command Window and press Enter.

You see Hello There George! as the output. The global variable really is accessible from another function.

Using subfunctions

A single function file can contain multiple functions. However, only one function, the primary function (the one that has the same name as the original file), is callable. Any other functions in the file, known as subfunctions, are local to that file. The primary function or other subfunctions can call on any subfunction, as long as that subfunction appears in the same file.

The main reason to use subfunctions is to simplify your code by breaking it into smaller pieces. In addition, placing common code in a subfunction means that you don’t have to copy and paste it all over the place — you have to write it only once. As far as anyone else is concerned, however, the file contains only one function. The inner workings of your code are visible only to you and anyone else who can view the source code.

Listing 9-1 shows an example of how a subfunction might work. You can also find this function in the SayHello6.m file supplied with the downloadable source code.

LISTING 9-1 Creating a Subfunction

function [ HelloString ] = SayHello6( Name )

%SayHello6()

% This function says Hello to everyone!

% It requires a string, Name, as input.

% It passes back the result as HelloString.

HelloString = [GetGreeting(), Name, '!'];

disp(HelloString);

end

function [ Greeting ] = GetGreeting ( )

Greeting = 'Hello There ';

end

This code is actually another version of the SayHello3 code that you worked with earlier. The only difference is that the greeting is now part of the GetGreeting() subfunction, rather than a simple string. Notice that SayHello6() can call GetGreeting(), using the same technique that it could use for any other function.

After you create this code, type Output = SayHello6('Stan') in the Command Window and press Enter. You see the following output:

Hello There Stan!

Output =

'Hello There Stan!'

The output is precisely as you expect. However, now type GetGreeting() and press Enter in the Command Window. Instead of a greeting, you see an error message:

Unrecognized function or variable 'GetGreeting'.

The GetGreeting() subfunction isn’t accessible to the outside world. As a result, you can use GetGreeting() with SayHello6() and not have to worry about outsiders using the subfunction incorrectly.

Nesting functions

You can also nest functions one inside the other in MATLAB. The nested function physically resides within the primary function. The difference between a primary function and a nested one is that the nested function can access all the primary function data, but the primary function can’t access any of the nested function data.

In all other respects, subfunctions and nested functions behave in a similar manner (for example, outsiders can’t call either subfunctions or nested functions directly). Listing 9-2 shows a typical example of a nested function. You can also find this function in the SayHello7.m file supplied with the downloadable source code.

LISTING 9-2 Creating a Nested Function

function [ HelloString ] = SayHello7( Name )

%SayHello7()

% This function says Hello to everyone!

% It requires a string, Name, as input.

% It passes back the result as HelloString.

HelloString = [GetGreeting(), Name, '!'];

disp(HelloString);

function [ Greeting ] = GetGreeting ( )

Greeting = 'Hello There ';

end

end

This is another permutation of the SayHello3() example, but notice how the GetGreeting() nested function now resides inside SayHello7(). After you create this code, type Output = SayHello7('Stan') in the Command Window and press Enter. You see the following output:

Hello There Stan!

Output =

'Hello There Stan!'

Using Other Types of Functions

MATLAB supports a few interesting additions to the standard functions. In general, these additions are used to support complex applications that require unusual programming techniques. However, it pays to know that the functions exist for situations in which they come in handy. The following sections provide a brief overview of these additions.

Inline functions

An inline function is one that performs a small task and doesn’t actually reside in a function file. You can create an inline function right in the Command Window if you want. The main purpose for an inline function is to make it easier to perform a calculation or manipulate data in other ways. You use an inline function as a kind of macro. Instead of typing a lot of information every time, you define the inline function once and then use the inline function to perform all the extra typing.

To see an inline function in action, type SayHello8 = inline('[''Hello There '', Name, ''!'']') in the Command Window and press Enter. Note that you’re using two single quotes in this case, not a double quote. You see the following output:

SayHello8 =

Inline function:

SayHello8(Name) = ['Hello There ', Name, '!']

This function returns a combined greeting string. All you need to do is type the function name and supply the required input value. Test this inline function by typing disp(SayHello8('Robert')) and pressing Enter. You see the expected output:

Hello There Robert!

Notice that the inline function doesn’t actually include the disp() function call. An inline function must return a value, not perform output. If you try to include the disp() function call by using the SayHello8 = inline('[disp(''Hello There '', Name, ''!'')]') function instead and calling it with SayHello8('Robert'), you see the following error message:

Error using inlineeval (line 15)

Error in inline expression ==> disp(['Hello There ', Name, '!'])

Too many output arguments.

Error in inline/subsref (line 24)

INLINE_OUT_ = inlineeval(INLINE_INPUTS_,

INLINE_OBJ_.inputExpr, INLINE_OBJ_.expr);

Anonymous functions

An anonymous function is an even shorter version of the inline function. It can contain only a single executable statement. The single statement can accept input arguments and provide output data.

To see how an anonymous function works, type SayHello9 = @(Name) ['Hello There ', Name, '!'] and press Enter. You see the following output:

SayHello9 =

@(Name)['Hello There ',Name,'!']

The at (@) symbol identifies the code that follows as an anonymous function. Any input arguments you want to accept must appear in the parentheses that follow the @ symbol. The code follows after the input argument declaration. In this case, you get yet another greeting as output.

To test this example, type disp(SayHello9('Evan')) in the Command Window and press Enter. You see the following output:

Hello There Evan!

You generally use anonymous functions for incredibly short pieces of code that you need to use repetitively. Inline functions execute more slowly than anonymous functions for a comparable piece of code. So whenever possible, use an anonymous function in place of an inline function. However, inline functions also provide the extra flexibility of allowing multiple lines of code, so you need to base your decision partly on how small you can make the code that you need to execute.

If you find an error or have any questions, please email us at admin@erenow.net. Thank you!