Chapter 11
IN THIS CHAPTER
Understanding Live Script
Creating a Live Script
Running a Live Script
Performing diagnostics
In the past, writing an application was all about writing code in a step-by-step, static manner, which works fine for a great many needs. Also, running regular code makes the results appear separately from the code, resulting in a disconnect between the two.
However, many people prefer to work with code in a dynamic manner so that they can see the result of a line of thought immediately after pursuing it. A Live Script is a technique of writing code that lets you work with your code dynamically and see the result alongside the code. This approach provides a less abstract method of creating MATLAB scripts. The first part of this chapter helps you understand how Live Script compares with a regular MATLAB script, allowing you to take what you’ve learned in previous chapters and build on it.
You use a special kind of editor, the Live Editor, to create a Live Script. This editor has a number of new features that you haven’t seen before now, but some features work the same as they do in the standard Editor. The next part of the chapter gets you started with the Live Editor.
Using sections, as described in the “Using the %% comment” section of Chapter 8, becomes more important when working with a Live Script because the idea is that you update only what is needed. The next section of the chapter discusses Live Script sections and explains how to use them when running your code.
As with anything else, you eventually find errors in your Live Scripts. Because of how you interact with Live Scripts, the debugging techniques are a little different from those you use when working with a standard script.
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\Chapter11 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, Chapter11a, to hold the results of the hands on exercises. See the Introduction for details on how to obtain the downloadable source.
Comparing a Live Script to a Regular Script
No magic is associated with a Live Script. You need to think in terms of extended functionality. Regular scripts are stored as code in a text file with an .m extension. On the other hand, Live Script relies on an .mlx file, which is an extension of the .zip file format. This .mlx file contains three types of content:
· Code
· Formatted content
· Output
The code and formatted content are combined into an XML document using the Office Open XML (ECMA-376) format. Using the .mlx file format has these advantages:
· Interoperability across locales: If you store your script using letters from one language and open the script back up using the editor for another language, the script will automatically appear with the correct lettering. So, this means that anyone should be able to read your code. However, MATLAB doesn’t magically translate the language, so comments and other textual elements still appear in the original language.
· Extensible: You can extend the formatting capability of your script to use all the formatting options found in Microsoft Word. You can implement some custom formatting options as well, but that topic is well beyond the scope of this book.
· Forward compatibility: The file format allows future proofing by implementing the ECMA-376 standard’s forward-compatibility strategy.
· Backward compatible: Future versions of MATLAB will support the features provided by previous versions of MATLAB.
As previously mentioned, the use of the .mlx file format allows other functionality as well. A standard script displays its output in the Command Window, and you must run it every time you start MATLAB. A Live Script stores its output in the same window as the code, and you save the output when you save the .mlx file. Using a Live Script saves considerable time and effort when you have to create similar reports each day, because you update only the parts that have changed.
To present nicely formatted output with a standard script, you must rely upon publishing markup, which is a method of telling the Live Editor how to format the text. For example, placing asterisks on either side of a word or phrase like this, *This is bold!*, will make the text appear in bold type. When working with a Live Script, the experience is more akin to working with a word processor. You use various controls to format the output directly so that you can see it immediately without having the run the code again.
Working with the Live Editor
The Live Editor has a different appearance and some different functionality from the standard Editor. However, many things are the same. For example, you use the same commands and functions. MATLAB has some features that the Live Editor doesn’t support, such as classes (see Chapter 13). In addition, because of how it works, Live Editor doesn’t support some MATLAB preferences, including custom keyboard shortcuts and Emacs-style keyboard shortcuts (see https://www.mathworks.com/help/matlab/matlab_env/about-editor-debugger-preferences.html for a more complete list). Working with nonstandard shortcuts is outside the scope of this book, but you can learn more about custom keyboard shortcuts at https://www.mathworks.com/help/matlab/matlab_env/keyboard-shortcuts.html, and about the Emacs-style shortcuts at https://blogs.mathworks.com/community/2007/05/11/setting-up-keybindings-for-the-command-window-and-editor/. With these differences in mind, the following sections get you started using Live Editor. You can also find this Live Script in the SimpleLiveScript.mlx file supplied with the downloadable source code.
Opening the Live Editor
You use Live Editor to edit Live Scripts and Live Functions. To open the Live Editor, choose any of these options:
· Click New Live Script on the Home tab.
· Click New ⇒ Live Script on the Home tab.
· Click New ⇒ Live Function on the Home tab.
The appearance of the Live Editor for Live Functions differs from Live Scripts, and you see these differences discussed in Chapter 12. Figure 11-1 shows how the Live Editor appears for Live Scripts. Note that you can click the x in the upper-right corner of the Welcome to the Live Editor pane to free up some space.
FIGURE 11-1: The Live Editor shows an Editor pane (left) and an Output pane (right).
Working with the Output pane
The Output pane is where you see the results of any code that you write and run. In addition, it shows formatted text you create and any graphics you include. The plots you develop also appear in the Output pane. What you end up with is a report made up of everything you’ve done. Use the following steps to see how all this works (the steps assume you’ve opened the Live Editor using one of the options in the previous section).
1. Click Text in the Text section of the Live Editor tab.
You see the current line (the one with the insertion pointer) change to a text line (notice there is no longer a number on the left side of the display).
2. Type This is a Sample Section and then select Heading 1 from the style drop-down list in the Text section of the Live Editor tab.
The formatting of the text you typed changes.
3. Press Enter to move to the next line; then click Code in the Code section of the Live Editor tab.
The line changes to a code line, where you can type code.
4. Type the following code in the code area of the document:
x = 1 + 2;
fprintf('X = %d', x);
plot(1:10, sin(1:10));
5. Press Enter and then click Section Break in the Section section of the Live Editor tab.
The Live Editor adds a blue line showing the end of the section.
6. Place the cursor anywhere within the current section; then click Run Section in the Section section of the Live Editor tab.
You see the result shown in Figure 11-2.
FIGURE 11-2: The Live Editor window displays the results from the formatted text, code, and plot.
The default setting for the Output pane is to show the output to the right. It’s the best view to use as you work through the coding process so that you can keep code and output separate. However, you have two other ways of displaying the Output pane by using the three buttons on the right side of the Output pane. Click the Output Inline button, and the display in Figure 11-2 changes to look like Figure 11-3.
FIGURE 11-3: Using the Output Inline view lets you see code and output together.
This is a good view to use when working with colleagues who need to know the details in a nicely presented manner. In many respects, the output looks like that presented by Jupyter Notebook (https://jupyter.org/), a product extensively used for research and other nondevelopmental needs.
Business viewers won’t care about the underlying details shown in Figure 11-3, so the next view might work better. Click Hide Code to see the output in a new way, as shown in Figure 11-4.
MATLAB combines the formatted text, code output, and plot all in one easily read form. You could print this view and use it for a presentation or other need. The point is that nothing has changed. Click Output on Right and you see the original view in Figure 11-2.
To save your file, click Save. When you see the Select File for Save As dialog box, type SimpleLiveScript in the File Name field and then click Save.
FIGURE 11-4: Using the Hide Code view creates a presentation ready report.
Adding formatted text
The previous section shows how to add a heading to a section. Of course, headings can appear anywhere needed. Live Editor supports five different paragraph styles:
· Normal
· Heading 1
· Heading 2
· Heading 3
· Title
Each of the paragraph styles offers presets for the text you need to include in your document. Below the style drop-down list are buttons for
· Bold
· Italics
· Underline
· Monospace
The Monospace option is especially helpful when you want to format text as code, but not use the actual code. This is a good option for explanatory text. The Text section also supports bullet lists, numbered lists, and the three standard text alignments. Figure 11-5 shows examples of the various kinds of formatting.
FIGURE 11-5: Examples of various text formatting features in Live Editor.
Using plots within the coded area
As demonstrated in the “Working with the Output pane” section, all you need to do to include a plot in your document is to provide the required code. However, you may find that the code becomes involved and you don’t want to have a lot of hard to read code in your report. Here’s a quick example:
x=linspace(0,2*pi,30);
y=sin(x);
z=cos(x);
plot(x,y,x,z);
You type this code into the Command Window to plot it. After plotting the data, you now save the resulting figure to a file named SinCos.fig. Simply click the Save Figure button in the Figure window. You can now add a simple piece of code, openfig('SinCos.fig');, to your Live Script document to use the figure. This technique works well if the figure changes regularly and you don’t want to include the code for recreating it in your Live Script, but do want to display the figure as part of your report. Figure 11-6 shows the output from this example.
FIGURE 11-6: Use a saved figure when necessary in your document.
Incorporating graphics
You can use graphics in a number of ways within MATLAB, such as when you perform image analysis (see Chapter 20 for an overview of performing analysis tasks). However, graphics can also add eye candy to a presentation to make your point clearer and the presentation more enjoyable. Anything you can do to maintain your audience’s interest will make your presentations more successful. Fortunately, you can use any of these graphics formats as part of a Live Script document:
· BMP (Microsoft Windows Bitmap)
· GIF (Graphics Interchange Files)
· HDF (Hierarchical Data Format)
· JPEG (Joint Photographic Experts Group)
· PCX (Paintbrush)
· PNG (Portable Network Graphics)
· TIFF (Tagged Image File Format)
· XWD (X Window Dump)
You usually used a two-step process to work with graphics in MATLAB: Read the graphic into a variable, and then display the content of the variable onscreen. The location of the graphic usually doesn’t matter as long as you have read access to the file and you have the proper permissions. The image used in the following example is a public domain offering from https://commons.wikimedia.org/wiki/Main_Page. Here’s the code you use to download and display the image shown in Figure 11-7 (the actual URL is longer; review the downloadable source to see it):
Img = imread('https://upload.wikimedia…Dog_face.png');
image(Img)
FIGURE 11-7: Add pizzazz to your document using graphics from any location.
Your graphics need not be static in MATLAB. For example, you can create an Acquire Webcam Image task, use it to connect to a webcam, and then perform as-needed tasks, as described at https://www.mathworks.com/help/supportpkg/usbwebcams/ug/acquire-images-from-webcams.html. To use this feature, you must install the MATLAB Support Package for USB Webcams.
Incorporating controls
Controls can make your documents interactive. You can do everything from very simple things, like displaying a Help button, to providing controlled inputs for your algorithm. You can even create input form documents or design a test. Using controls gives your application more of a full-fledged application feel without requiring you to get a computer science degree. The experience of using controls isn’t free of some development tricks, but using the MATLAB controls is easier than working with controls in a full-fledged development environment. MATLAB supports these controls:
· Numeric Slider: A numeric slider allows control over a value within a specific range and prevents users from entering non-numeric values. For example, you might want to allow the viewer to choose the number of graphs displayed at any time as part of the plot. Moving the Numeric Slider control’s thumb (the square box that controls its value) to the desired number of graphs will change the appearance of the plot. The advantage of using a numeric slider is that you control the correct input values and don’t need to consider values outside the desired range, reducing application errors.
· Drop-Down List: A drop-down list box contains a set number of input values. The user selects the desired input value from the list, meaning that incorrect input values due to typos and other forms of user error are a thing of the past. Relying on drop-down list boxes instead of requiring the user to type values also makes data entry significantly faster.
· Check Box: A check box is a logical input, and you obtain one of two values from it. The feature is either on or off; the answer is either yes or no; and the user either wants to opt in or opt out.
· Edit Field: An Edit Field control provides a convenient means of allowing freeform input from the user. Avoid using the Edit Field control when you can, because it creates a potential security breach unless you perform a lot of background checks. The Edit Field control is the most flexible of all the controls because you really can perform free-form input.
· Button: A Button control enables you to define the precise moment when an action should occur. For example, after providing all the input required to create a plot, the user clicks the Plot button in your application and sees the resulting plot onscreen. To use the Button control effectively, you must set the Run field for any controls in the document to Nothing.
Controls require a certain amount of configuration before you use them. The following steps help you create a simple control example in which the user selects a value from a Numeric Slider control, and clicking a Button displays that value.
1. Choose Numeric Slider from the Control drop-down list in the Code section of the Live Editor tab.
You see the slider, along with its fields as shown in Figure 11-8. Modifying the settings immediately will ensure that you don’t forget to do so later. However, you can change the configuration later by right-clicking the control and choosing Configure Control from the context menu.
FIGURE 11-8: Controls provide access to settings through a configuration dialog box.
2. Type A Value in the Label field.
The next three settings control the minimum Numeric Slider value, the maximum value, and the increments between each change as the user moves the thumb.
3. Type 0 in the Min field.
4. Type 5 in the Max field.
5. Type 1 in the Step field.
6. Choose Nothing in the Run field.
This last setting is especially important because it allows you to control interactions with the Numeric Slider control using the Button control.
7. Go to the next line of the document and choose Button from the Control drop-down list in the Code section of the Live Editor tab.
You see a control configuration dialog box.
8. Type See Value in the Label field.
The Run field determines how much of the document the Button controls. The default setting of Current Section is sufficient for this example, but you should review the other options as well.
9. Place the cursor anywhere within the section; then click Run Section in the Section section of the Live Editor tab.
The application displays the current value, which is 5 (see Figure 11-8), as shown in Figure 11-9.
FIGURE 11-9: The controls all have default values when you run the section.
10. Move the slider to a value of 3.
Notice that the output doesn’t change.
11. Click See Value.
The output changes to match the new value.
Running Live Script Sections
Knowing how to run a Live Script can save a lot of time. This chapter runs every example using the Run Section option. If you’re building an application or performing updates, using Run Section ensures that you execute only the current section. When the rest of your code works, there is no reason to keep running it repeatedly. It’s not that your computer will wear out or get annoyed — it’s more a matter of preserving your time. Adding extra code to each execution will slow you down.
Of course, if you make changes to those previous sections, you need to run the code starting from the changed section to your current location. When the current location is the end of the file, you simply place the cursor where the change occurred and then choose Run to End. This button saves you from having to click Run Section repeatedly.
Another option for running Live Script sections is to rely on Run and Advance. The Run Section option keeps the cursor in the currently selected section. However, Run and Advance runs the code in the current section and then moves to the next section. Using this approach allows you to run the entire document one section at a time.
Clicking Run will execute the entire document. The cursor doesn’t change positions. You use this option when you need to update the entire document and are sure that the update will succeed. This is the fastest way to run your Live Script code.
Diagnosing Coding Errors
Even with the simplified approach that the Live Editor relies on for coding, your code could still contain errors. Errors are called bugs, and removing the bugs is called debugging. The Live Editor doesn’t offer strong debugging features like ones that developers use, but you still have access to a range of debugging options.
The editor is quite determined to save you from yourself. For example, when you type something wrong in the editor and MATLAB recognizes it as an error, you see a red line under the errant text with a message explaining what it thinks has gone wrong, as shown in Figure 11-10. In fact, examining your document for red underlines could save you a lot of work.
FIGURE 11-10: Look for red lines under your code because they’re errors.
Removing the semicolons from the ends of your lines of code can also help you locate errors by showing the output from suspect code. You don’t have to remove all the semicolons, which can take a lot of time; just remove them for calls that you suspect. Run the section again to determine whether you made a wrong assumption somewhere.
The debug type features that the Live Editor provides allow you detailed running of code lines. The Step drop-down list in the Run section of the Live Editor tab contains options to
· Step: Runs a single line of code so that you can see how the function call performs.
· Step In: When calling your own custom functions, you step into those functions from the current thread of execution by clicking Step In. This feature lets you take a detailed look at the code to see whether it has any underlying problems.
· Step Out: After examining a particular function, clicking Step Out takes you one level up so that you’re back to where the function was called in your script. Otherwise, you’d need to single-step through the entire function.
· Run to Cursor: If you know where a problem occurs, you can place the cursor there and run the code from the current location to the problem area. Sometimes, focusing on a specific area of the code helps you locate the source of errors.
Clicking Step places the Live Editor into a debugging mode, and the editor’s controls change, as shown in Figure 11-11. The current line of code is highlighted in light green, so you know where you’re executing the code.
FIGURE 11-11: A change in the editor appearance tells you that you’re in debug mode.
The Step drop-down list enables the options that are useful to the current situation. In this case, you’d click Step to see the next line because you aren’t calling a function. If you want to continue the execution of the current section, you click Continue. Likewise, if you think you’ve found the error, you click Stop, fix it, and try again.
After you execute the code to create variables, you can see each variable’s value by hovering the mouse over it. This technique makes it very fast to determine whether a variable contains what you think it should contain. Other debugging techniques are available, but they’re common to all the editors, so Chapter 18 covers those.