Chapter 12
IN THIS CHAPTER
Understanding the Live Function difference
Using functions to start Live Functions
Combining Live Functions with Live Scripts
Chapter 11 discusses Live Scripts, which are the counterpart to scripts in MATLAB. Live Functions represent the counterpart to functions in MATLAB as well, and they embody many of the same characteristics as Live Scripts do. For example, you use the Live Editor when working with Live Functions (see the “Working with the Live Editor” section of Chapter 11 for details). However, there are significant differences between Live Scripts and Live Functions, even in the manner of creating them in the Live Editor. This chapter helps you understand where Live Functions fit in with functions and Live Scripts as part of your MATLAB development strategy.
One of the things that sets Live Functions apart from their plain function alternative is the flexibility they provide in creating reusable code. This chapter helps you understand the flexibility that Live Functions provide and demonstrates how you can move your current functions to Live Functions. More important, this chapter helps you understand whether to use functions or Live Functions as your development strategy. Sometimes using the simpler function can be better if you don’t actually need the special features that Live Functions can provide.
Live Functions can stand alone, just as functions do. However, you gain the most power from combining Live Functions with Live Scripts as needed. In fact, when performing complex analysis, the combination of Live Scripts and Live Functions can be unbeatable in creating a solution that’s ultimately simpler than any other means at your disposal.
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\Chapter12 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, Chapter12a, to hold the results of the hands-on exercises. See the Introduction for details on how to obtain the downloadable source.
Comparing a Live Function to a Regular Function
A regular MATLAB function exists in a text file that uses an .m file extension. Chapter 9 tells you about various kinds of functions and demonstrates how to create them. A Live Function exists within an .mlx file, just as a Live Script does, with all the added functionality described in the “Comparing a Live Script to a Regular Script” section of Chapter 11. You can also add formatted text, images, hyperlinks, and equations to Live Functions — something that isn’t available with a regular function.
The most important difference between Live Functions and regular functions is that it’s easier to partition a Live Function using sections. The benefits of working with sections become especially noticeable when using the following (as explained in Chapter 9):
· Subfunctions (also called local functions)
· Nested functions
· Inline functions
· Anonymous functions
Sections enable you to separate these elements so that they’re easier to see, test, and debug. Suddenly, instead of one huge bulky piece of text, you work with small, individual elements that are easier to understand. So, the actual function may not differ much between Live Functions and regular functions, but your perception of them will, which can reduce the work required to interact with code you didn’t write, or wrote a long time ago.
You call both functions and Live Functions from outside the function file. The easiest form of access is from the Command Window. However, you can also call them from scripts and Live Scripts. In contrast to functions, you can merge (create a single entity) from a Live Script and a Live Function, as described in the “Merging Live Functions and Live Scripts,” near the end of this chapter.
Understanding Live Function Flexibility Differences
The easiest way to understand the flexibility differences between a Live Function and a regular function is to create and interact with a Live Function. The following sections assume that you’ve already worked with the Live Editor, as explained in the “Working with the Live Editor” section of Chapter 11. These sections focus on differences between these Live Functions and regular functions, but they also help you understand differences between Live Functions and Live Scripts.
Creating a Live Function
The following steps help get you started creating your first Live Function. You can also find this Live Function in the DoAdd.mlx file supplied with the downloadable source code.
1. Choose New ⇒ Live Function in the File section of the Home tab.
You see the new Live Function shown in Figure 12-1. Comparing this figure with Figure 11-1 shows that the beginning of a Live Script looks different from that of a Live Function. A Live Function starts with a text section for documentation purposes and a code section for the actual function code.
The Live Editor may display a warning message for the newly created function. This is because you haven’t given the function a name and haven’t saved the file, so you can safely ignore the warning for now.
FIGURE 12-1: A Live Function begins with two sections: one text and one code.
2. Change the first text line to read: Add Two Numbers.
3. Change the second text line to read: Provide the x and y input values to receive the summed output value.
4. Change the untitled entry in the first code line to read DoAdd.
5. Click Save in the File section of the Live Editor tab.
You see the Select File for Save As dialog box, shown in Figure 12-2. Notice that the dialog box automatically suggests DoAdd.mlx as the filename.
6. Click Save.
The Live Function is added to the current directory.
FIGURE 12-2: Save the file using the name of the function you created.
Running a Live Function
One of the first things you notice when working with a Live Function is that you can’t click any of the run options in the Section or Run sections of the Live Editor tab. Instead, you run a Live Function just as you would a regular function. To try the function shown in the previous section, type DoAdd(1, 2) and press Enter in the Command Window. You see:
ans =
3
However, there is a difference when obtaining help for a Live Function. Type help('DoAdd') and press Enter. The help text looks like this:
DoAdd Add Two Numbers
z = DoAdd(x, y)
Provide the x and y input values to receive the summed output value.
Documentation for DoAdd
When you click the Documentation for DoAdd link, you see a Help dialog like the one shown in Figure 12-3. DoAdd() is a simple function, so there isn’t much documentation for it. However, as you add formatted text, images, hyperlinks, and equations to the documentation, the output of the Help dialog box also changes. Everything you add to the function also appears as part of help, making your function significantly easier to use.
FIGURE 12-3: Help works differently for Live Functions; you get more, with less effort.
Refactoring a Live Function
As you work on your functions, you might be amazed at just how quickly they grow, often becoming unmanageable. The problem is that you’ve already invested a lot of time and effort in creating the function, so rewriting it is unappealing. Refactoring, the process of moving pieces of code around without changing its functionality, is often the right answer for this situation. For example, consider the code in Listing 12-1.
LISTING 12-1 An Integer Version of DoAdd()
function z = DoAddInt(x, y)
try
if isreal(x) && rem(x, 1) == 0
x = int64(x);
else
disp('Value x isn''t an integer.')
return;
end
catch
disp('The input is non-numeric.')
return;
end
try
if isreal(y) && rem(y, 1) == 0
y = int64(y);
else
disp('Value y isn''t an integer.')
return;
end
catch
disp('The input is non-numeric.')
return;
end
z = x + y;
end
The function certainly isn’t huge, but it contains redundant code, and it would be easier to read if that redundant code appeared in a separate function. You could refactor the redundant code into a single local function using these steps.
1. Remove the first two return; statements so that the first block of redundant code looks like this:
try
if isreal(x) && rem(x, 1) == 0
x = int64(x);
else
disp('Value x isn''t an integer.')
end
catch
disp('The input is non-numeric.')
end
You can’t refactor code that contains return; statements. MATLAB displays an error message if you try.
2. Highlight the code block shown in the previous step and then choose Refactor ⇒ Convert to Local Function in the Code section of the Live Editor tab.
MATLAB refactors the code so that it appears like the code shown in Figure 12-4.
The result in Figure 12-4 still isn’t quite right, but it’s close.
FIGURE 12-4: MATLAB refactors the code by creating a local function.
3. Type CheckInt to provide a valid function name.
Notice that the name of the new function changes in both places.
You need some method of determining whether x is actually an integer, so the next step adds a special x output to the two error outputs.
4. Add return value statements to the local function, as shown in bold:
function x = CheckInt(x)
try
if isreal(x) && rem(x, 1) == 0
x = int64(x);
else
disp('Value isn''t an integer.')
x = nan;
end
catch
disp('The input is non-numeric.')
x = nan;
end
end
You can now check for nan (not a number) as part of the main function. In addition, you can use the same approach for the value y.
5. Modify the DoAddInt() function so that it looks like this:
function z = DoAddInt(x, y)
x = CheckInt(x);
if isnan(x)
return;
end
y = CheckInt(y);
if isnan(y)
return;
end
z = x + y;
end
Compare this version of DoAddInt() with the version found in Listing 12-1 and you see that this version is simpler.
Refactoring to a local function is a good idea when the refactored code is unique to the Live Function or Live Script that uses it. However, you might decide that you want to use a particular piece of code in a number of your Live Scripts and Live Functions. If this is the case, you highlight the section of code you want to refactor and reuse; then you choose Refactor ⇒ Convert to Function in the Code section of the Live Editor tab. MATLAB will create a new file that contains the code in question. You make the same sorts of modifications as shown earlier in this section, except that you make them in the separate file.
Using the specialized coding buttons
Specialized features can make your coding experience easier and possibly save time as well. MATLAB provides a set of six specialized coding buttons in the Code section of the Live Editor tab, as shown in Figure 12-5.
FIGURE 12-5: Use these specialized buttons to save time and effort.
Table 12-1 provides you with a quick summary of how you use each button to perform tasks in the Live Editor.
TABLE 12-1 Live Editor Coding Buttons
Button Name |
Speed Key |
Purpose |
Comment |
Ctrl+R |
Adds a % in front of each selected line in a group, commenting the code out for testing or debugging. |
Uncomment |
Ctrl+T |
Removes the first % in front of each selected line in a group, making the code active again. If the group contains a comment line, only the first % is removed, which means that the comment stays a comment. |
Wrap Comments |
Ctrl+J |
Combines lines with a similar indent to make a comment block smaller. Works only with lines that are already commented out. |
Smart Indent |
Ctrl+I |
Adds indentation as needed to make the code more readable. MATLAB uses natural code boundaries, such as if…else statements, to make the indentation. |
Increase Indent |
Ctrl+] or Tab |
Adds a single level of indentation to the selected lines of code. |
Decrease Indent |
Ctrl+[ or Shift+Tab |
Removes a single level of indentation from the selected lines of code. If the selected code is already at the left margin, the button has no effect on that line. |
The Smart Indent button requires a little more explanation. When you click this button, MATLAB uses the default indentation scheme, which appears in Listing 12-1. However, some people prefer to have function code indented within the function block. Consequently, you must select the function code (without the function declaration and final end) and use Increase Indent to obtain the desired result. Here’s the modified version of DoAddInt() with function level indentation added:
function z = DoAddInt(x, y)
x = CheckInt(x);
if isnan(x)
return;
end
y = CheckInt(y);
if isnan(y)
return;
end
z = x + y;
end
Many people find this form of indentation easier to read because the function boundaries stick out more. However, the use of sections in Live Editor tend to make the function boundaries more obvious as well. So, whether you indent function code or not is a matter of personal taste.
Going to a specific function
If your function file contains a number of functions, locating a particular function can be difficult. To make things easier, you can use the Go To drop-down list in the Navigate section of the Live Editor tab. When you click the down arrow, you see a list of function names in the currently selected file similar to those shown in Figure 12-6. Simply click the function you want to work with.
FIGURE 12-6: Use the Go To drop-down list to access functions quickly.
Converting a Function to a Live Function
You don’t have to start from scratch to use a Live Function. MATLAB provides the means to use existing code, such as SayHello3.m from Chapter 9. Use these steps to copy SayHello3.m from the Chapter09 folder to the Chapter12 folder used for this chapter.
1. Right-click SayHello3.m in theChapter09 in the Current Folder window and choose Copy from the context menu.
MATLAB places a copy of the file on the Clipboard.
2. Right-click in the Chapter12 folder and choose Paste from the context menu.
You see a copy of SayHello3.m placed in the Chapter12 folder.
At this point, you can open SayHello3.m as a Live Function by right-clicking the file and choosing Open as Live Function from the context menu. MATLAB performs the required conversion for you automatically, as shown in Figure 12-7.
FIGURE 12-7: MATLAB automatically converts the format of your function file.
Notice that the file no longer uses the document format used for functions:
%SayHello()
% This function says Hello to everyone!
% It requires a string, Name, as input.
% It passes back the result as HelloString.
The documentation automatically appears in the form used for a Live Function. When you save the function, it receives the name SayHello3.mlx, which means you now have two functions with the same name. Change the word Hello to Goodbye in the HelloString = ['Hello There ', Name, '!']; line of the function and save the Live Function to disk. Now type SayHello3('John') and press Enter. You see this output showing that MATLAB will execute the Live Function before it executes the standard function.
Goodbye There John!
ans =
'Goodbye There John!'
When there are two files, one Live Function and one normal function, with the same function name, MATLAB always executes the Live Function. This means that if you have a naming conflict, you may obtain an unexpected result from your code. Always ensure that the standard functions you plan to use have a different name from the Live Functions in the same folder.
Sharing Live Functions and Live Scripts
Eventually, you’ll want to show off your work to impress colleagues or as a means of teaching students. The “Publishing information” section of Chapter 8 describes how to publish your script, which isn’t quite the same as sharing a Live Function or Live Script. You have these options when sharing a Live Function or Live Script:
· Interactive document
· Full screen presentation
· Plain text
· Static document
The following sections provide an overview of these methods of sharing your code with others. Each technique has benefits, so you should use the approach that best meets your specific sharing need.
Using an interactive document
You can simply send the .mlx file to others. It’s recommended that you hide the code for any Live Script you send out this way so that recipients focus on the results rather than the underlying code. This is the option to use for peer review. Anyone receiving the file will have full access to your code because MATLAB doesn’t provide any form of document protection such as that found in applications like Microsoft Word. So, the downside of this approach is that you won’t be able to hide any great ideas from view — everything is open to everyone.
Employing a full screen presentation
When providing a presentation in public, you can place MATLAB in full-screen mode by choosing Full Screen in the Display section of the View tab. What you see is a help-type display that works exceptionally well for teaching needs.
A Live Function display will show the function documentation and code. When working with a Live Script, you can show the output to the right, in line with the code, or hide the code from view. To change the view, move the cursor to the top of the screen to display a Toolstrip containing these tabs:
· Live Editor
· Insert
· View
To leave full-screen mode, press Ctrl+F11 or Full Screen in the Display section of the View tab. Note that MATLAB places the full-screen display on the primary screen of a two-or-more-screen computer, so you can have MATLAB on a secondary screen and display the primary screen for your audience.
Working with plain text
Even though it’s a big step backward, you can save your Live Function or Live Script as a plain function or plain script for those who have older versions of MATLAB. To perform this task, choose Save ⇒ Save As in the File section of the Live Editor tab. You see a Select File for Save As dialog box like the one shown previously in Figure 12-2. Choose MATLAB Code Files (UTF-8)(*.m) in the Save as Type field; then click Save.
The resulting file converts any special Live Function or Live Script features to comments. Figure 12-8 shows an example of the SimpleLiveScript.mlx file from Chapter 8. It’s definitely less informative than using a Live Script (see the figures in Chapter 11 as examples), but the result does provide the essential code and the details as comments.
Creating a static document
Sharing your Live Function or Live Script as a static document makes it easier for people who lack a copy of MATLAB to interact with you. In addition, this method of sharing is better when you want to focus on Live Script output rather than code, with a greatly reduced chance of anyone’s seeing the code at all. This is also a great method for producing handouts for a class or other presentation venue.
FIGURE 12-8: Live Function and Live Script features are converted to comments when using plain text.
To use this technique, make sure you have the document you want to share selected in the editor. Choose one of the Export options on the Save drop-down list found in the File Section of the Live Editor tab. You have access to these output formats:
· Word
· HTML
· LaTeX
This option also supports a batch mode. Choose Save ⇒ Export Folder, and you see the Export Files in Folder dialog box, shown in Figure 12-9. You can export the files to any of the four supported file formats. In addition, you can choose the source and target folders, require MATLAB to ask before overwriting any existing output files, and request that MATLAB also copy supporting files, such as graphics. Just configure the dialog box options and click Export to make the process happen.
FIGURE 12-9: Use batch mode when converting a large number of code files.
Performing Comparisons and Merges
Managing code files can become cumbersome when you start to create multiple versions of the same file. In addition, you may want to move useful features from one file to another without having to cut and paste the changes. The act of checking two files for differences is comparison, while the act of moving differences from one file to another is merging. The following sections explain both activities.
Comparing Live Functions and Live Scripts
Sometimes you need to know how one file differs from another file, which isn’t hard if the two files are short. However, performing a manual comparison of two larger files is problematic because even the most astute viewer will likely make errors. To avoid this problem, you can ask MATLAB to perform the comparison for you. For example, consider the differences between DoAdd.mlx and DoAddInt.mlx. Use these steps to perform a comparison:
1. Right-click the source file or folder and choose Compare Against ⇒ Choose from the context menu.
The example uses the DoAdd.mlx file. You see the Select Files or Folders for comparison dialog box, shown in Figure 12-10. Note that you can perform either individual file comparisons or complete folder comparisons.
FIGURE 12-10: Choose the source and target file or folder, plus a comparison type.
2. Add a file or folder to use for comparison to the Second File or Folder field.
You can use the browse button to locate the file or folder as needed. The example uses the DoAddInt.mlx file.
3. Choose a Comparison Type drop-down list box entry.
The entries you see depend on the kind of comparison you perform. When working with Live Function or Live Script files, you can choose from Live Code Comparison (the kind used for this example) and Binary Comparison (which provides a very low-level view of file differences).
4. (Optional) Select Include Subfolders.
This option is available only when comparing folders that contain subfolders.
5. Click Compare.
You see the output of the comparison. Figure 12-11 shows the comparison for this example. Even though you can’t see it in the print book, MATLAB color-codes the comparison so that you can see modifications, additions, and deletions.
FIGURE 12-11: The comparison shows modifications, additions, and deletions.
Merging Live Functions and Live Scripts
The previous section of the chapter tells you how to see differences between two files. You can also use this approach for seeing differences between file folders. Whether the changes appear in files or folders, you can use a special Merge mode in MATLAB to move differences from one file to another. The process begins in the Comparison dialog box (refer to Figure 12-11). In that dialog box, click the Merge Mode button in the Merge section of the Comparison tab to show the Merge tab shown in Figure 12-12.
FIGURE 12-12: Use Merge Mode to move differences from one file to another.
Notice that there are now document icons with right-pointing arrows next to each change. To move a change from one document to another, simply click the button. The movement always occurs between the source document on the left to the target document on the right. Consequently, opening the files in the correct order is essential. Clicking Swap Sides only changes the view — movement still occurs from the original source document to the target document.
After you complete the required moves, click Save Result in the Finish section of the Merge tab. MATLAB won’t save the changes to the original target document. Instead, it recommends an alternative filename in the Select File for Save As dialog box. Click Return to Comparison to perform more document comparison tasks.