Chapter 14
IN THIS CHAPTER
Considering the app design approach
Creating a basic app
Testing the app
Packaging the app
Conceptually, a MATLAB app is about the same as any other app, except that it reflects the origin of its creation. In other words, you won’t find the next sophisticated gaming program as a MATLAB app. Likewise, you won’t build a word processor or a web app using MATLAB. A MATLAB app puts a nice interface on the various pieces of code you’ve built, and it enables you to view that code as an application. So if you’ve created scripts and functions to interact with sensors, you can now build an application to see the data without worrying about the underlying code. The first section of this chapter gives you additional app details, including how to work with the App Designer.
The next three sections of the chapter tell you how to create, test, and package a MATLAB app. When you’re done, you’ll have a packaged app that you can send to someone or share online with other MATLAB users. Even if you don’t share your app with anyone else, just having all your code neatly packaged will make it a lot easier to use. Note that you need to know about MATLAB classes, as discussed in Chapter 13, to build apps.
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\Chapter14 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, Chapter14a, to hold the results of the hands on exercises. See the Introduction for details on how to obtain the downloadable source.
Working with the App Designer
The App Designer is the starting point for creating a MATLAB app. However, before you start the App Designer, you want to know a little more about apps, such as what apps can do and where you can find example apps to use as templates for your own app. The following sections help you become acquainted with apps and help you get started with your first app by starting the App Designer.
Understanding apps
An app helps you automate tasks in a way that scripts, functions, Live Scripts, and Live Functions really can't. The difference is the inclusion of a Graphical User Interface (GUI), where app users configure the characteristics of a calculation just as they would when using any other custom app. You create a GUI that helps guide the user into the correct sequence of events, and the user doesn’t worry about working with code at all.
Apps use a special file format. The “Understanding the MATLAB files and what they do” section of Chapter 4 describes the .mlapp and .mlappinstall files associated with apps. When creating an app, you begin with the .mlapp file, which stores things like the GUI you create for your app. You see how this process works as the chapter proceeds, so just know for now that you’ll be working with a different file type than you’ve used in the past.
Of course, you might wonder about all the extra work required to create an app. After all, you could simply provide a set of written instructions for the existing code you’ve created. There are good reasons for using apps, such as these:
· Reducing human errors due to a misunderstanding of required input, values, or processes
· Increasing the number of people who can work with your code by reducing the complexity of the process
· Ensuring that people will actually work with your code by making the process easier
· Improving output results because everyone will use the same consistent process
· Removing ambiguity from the data analysis
· Creating a single package for the entire app so that you don’t have to worry about some pieces getting lost
· Defining an environment in which all the code elements are designed to work together so that you don’t encounter version differences
Getting apps
You should play with a few apps before you start designing your own. For one thing, playing with other people’s apps will help you see what works and what doesn’t in the way of design. You also gain insights into what you need to include as part of your app so that it works properly. There are currently three sources for apps:
· Toolboxes: Some toolboxes come with apps to make the toolbox easier to use. You can find some of these toolboxes at https://www.mathworks.com/help/referencelist.html?type=app.
· File Exchange: Many people have already developed apps for MATLAB. In fact, you might find the app you need and not need to develop an app of your own. You can find a list of community-supported apps at https://www.mathworks.com/matlabcentral/fileexchange/?term=type%3A%22App%22.
· Other users: The people who work in your community might actually be the best source of apps. They likely encounter the same problems that you do, so they may have created an app to solve the problem.
MATLAB makes it easy to locate new apps to try. Click Get More Apps in the File section of the Apps tab to display an Add-On Explorer window similar to the one shown in Figure 14-1. The left side of the window provides filters that you can use to narrow your search. The right side of the display shows the apps that match any filtering you use. Notice especially the Using MATLAB/App Building category, which you can use to locate examples specific to app building.
One of the more interesting examples is regexpBuilder. You can find it in the Using MATLAB/Language Fundamentals category (you may have to select the Data Types subcategory). When you select this app, you see a page similar to the one shown in Figure 14-2. To install regexpBuilder, follow these steps:
1. Click Add.
Add-On Explorer asks for your email address and password for verification. You then see a license agreement dialog box, where you click I Accept. The app downloads and becomes available for use. Unfortunately, you don’t see it in the Apps list.
2. Click Get More Apps in the File section of the Apps tab.
You see the Add-On Explorer display, shown in Figure 14-1.
3. Locate the regexpBuilder app again.
This time you notice an Open Folder button.
FIGURE 14-1: Use the Add-On Explorer to locate potential apps to try.
FIGURE 14-2: When you find an app you like, add it to your MATLAB setup.
4. Click the Open Folder button.
You see the regexpBuilder.mlappinstall file in the Current Folder window, as shown in Figure 14-3.
FIGURE 14-3: Locate the required installation file.
5. Right-click the regexpBuilder.mlappinstall file and choose Install from the context menu.
You see the Install dialog box shown in Figure 14-4, which asks where you want to install the app (you may not be able to select any tab other than Apps). In general, you want to keep your apps in the Apps tab to make them easy to find.
6. Click Install.
You see regexpBuilder appear in the Apps section of the Apps tab. The app is ready to use.
FIGURE 14-4: Choose an installation location for the app.
Remember that you can click the Back button in the Current Folder window to move from the regexpBuilder folder to your code folder again. You could also select the folder from the drop-down list box showing the previous folder history.
At this point, you can give regexpBuilder a try. Click the regexpBuilder entry in the Apps section of the Apps tab to display the window shown in Figure 14-5. Now that you have the app, take some time to play with it using the examples found at https://www.mathworks.com/help/matlab/ref/regexp.html. The results are comprehensive.
FIGURE 14-5: regexpBuilder helps you build regular expressions for use in MATLAB.
Starting the App Designer
It’s time to look at the App Designer. You use it to create your app or to view other people’s apps, assuming that they send you the .mlapp file. Click Design App in the File section of the Apps tab to display the App Designer Start Page, shown in Figure 14-6.
The banner at the top of the window is important because it provides access to a number of interesting bits of information (simply click the right- or left-pointing arrows on each side of the banner as needed). The first of these banner entries tells you about a three-minute tutorial that is worth trying if you want to get a little additional hands-on time.
FIGURE 14-6: Building an app starts with the selection of a template.
Immediately below the banner are template sections. The first of these sections simply says New, and this is where you choose a template for your app. Below the New category are various categories that cover important areas of app development:
· Examples: General
· Interactive Tutorial
· Respond to Numerical Input
· Respond to User Selections
· Embed HTML Content
· Lay Out Controls in a Grid
· Examples: Programming Tasks
· Link Data to a Tree
· Analyze an Image
· Configure a Timer
· Display Specialized Axes
· Create a Table
· Query Website Data
· Pass Data Between Apps
When you select one of the example entries, you open a predefined app like the one shown in Figure 14-7. You can try out this app, look at the underlying code by clicking Code View, and even use it as a starting point for your new app. Figure 14-7 shows the Respond to Numerical Input example (with the Designer tab selected), which is the Mortgage.mlapp file. As you work with the example file, MATLAB displays helpful balloon notes, such as one telling you about the need to add callbacks (a special kind of method) to the app. When you get done examining an app, simply close the App Designer (you need to restart the App Designer to view another example).
FIGURE 14-7: Looking at the examples can provide insights into building your own app.
The Respond to Numerical Input example relies on the 2-Panel with Auto-Reflow template. In fact, all the examples rely on one of three templates supplied as part of the App Designer (all of which appear in the New section). For this chapter, you need to create a new app using the Blank App template. To create the new blank app, open the App Designer Start Page (refer to Figure 14-6) and click Blank App in the New category. You see the blank App Designer display, shown in Figure 14-8 (with the Canvas tab selected).
FIGURE 14-8: The example in this chapter begins with a blank design area.
The initial view shows you the Component Library, which contains the components you use to build an interface, on the left side of the display. In the center is the canvas used to draw your interface. The right pane is the Component Browser, which you use to configure the components on the canvas.
The canvas provides two views. The first is Design View, which provides a graphical view of your app. The second is Code View, which shows the underlying code used to interact with the app components.
At the top of the display are two tabs. Designer gives you the controls needed to interact with the app as a whole. Canvas contains the controls needed to help you create a better interface. For example, there are controls used to align the app components, arrange them in specific ways, or space them evenly across the canvas. You can also choose to use various design aids, such as a grid to see how components will align better. The sections that follow offer more insights into how everything works.
Defining an Interface
The process of creating an app begins with the interface — how the app will look. The interface should tell a story of a sort. Whatever your app will do, the interface should help the user understand its purpose and the process used to make the interface work. Unfortunately, this chapter doesn’t have the space to provide a complete set of design guidelines for apps, but you can find many guidelines online like the one at https://docs.microsoft.com/en-us/windows/win32/uxguide/how-to-design-desktop-ux. Because the user experience tends to differ by device, make sure to use a design that will work for your target device, which, for MATLAB apps, is likely to be a desktop system. The following sections get you started with a simple interface for the example app.
Understanding the various components
A component is an individual control that you can add to your app, such as a button. Using components enables you to put your app together quickly without having to draw your own set of controls. In addition, using components gives your app a consistent look and feel with other MATLAB apps. Figure 14-9 shows the components used to create apps.
FIGURE 14-9: Using these components will make app design faster and easier.
The list of components that MATLAB provides is somewhat limited compared to other products and languages, but the number of components is sufficient for the kinds of apps that most people create. The example app will show a customized message with a selected piece of data in a particular format. The purpose of this app is to help you become acquainted with a variety of components. To begin, it’s helpful to select Show Grid in the View section of the Canvas tab so that you can more easily align the components. Selecting this option automatically selects Snap to Grid, in most cases as well (because it’s selected by default).
The top of the application should have a title so that everyone knows the app name. You need an Edit Field (Text), as contrasted to an Edit Field (Numeric), to provide a place for the user to type a name. Below the name entry, you add a Date Picker with the current date selected, and a Drop Down to select the date format. The Drop Down will have a first entry of Default Date to allow selection of the default date format. It’s important to wait for the user to make selections before doing anything, so below the date selections, you provide a Button for the user to request the formatted message. A Label will receive the formatted message, so you need to resize it to receive the information. Figure 14-10 shows the interface for the example application.
FIGURE 14-10: The example app uses a top-to-bottom design.
After you finish adding the components, saving your app is a good idea. Click Save in the File section of the Designer or Canvas tab, and you see the Save File dialog box. MATLAB doesn’t automatically suggest a filename for you, so type DateDisplay.mlapp in the File Name field and click Save.
Even though the list of components in the Component Library is fixed, you can create custom components. The process requires advanced programming skills, and component implementation is outside the scope of this book, but you can discover details at https://www.mathworks.com/help/matlab/creating_guis/develop-classes-of-ui-component-objects.html. Starting with the R2020b MATLAB release, you can create a class implementation for your UI components by defining a subclass of the ComponentContainer base class instead of using a script or function. None of your custom components will appear in the Component Library list, so you simply need to know that they exist to use them.
Changing the component properties
The layout shown in Figure 14-10 will probably work fine, but the app itself won’t work well because no one will know what to type in each of the fields. To make this app work, you need to define component properties. Begin with the first Label. You want to provide a welcoming message to people using your app, so select the label and then type Welcome to the Date Display App! in the Text property of the Component Browser. The message isn’t very exciting yet. Select Center for the HorizontalAlignment property value, type 16 in FontSize, and select B in FontWeight. The label looks better.
Note that some components contain two items, so you must select the item you want to work with. For example, an Edit Field (Text) consists of a label and a text box. To change the label, you must specifically select it, as shown in Figure 14-11.
FIGURE 14-11: Make sure to select the element you want to work with in a component.
Now that you know how to interact with the components, it’s time to complete the setup. Table 14-1 shows the settings for the other components for this app.
After you make the changes shown in Table 14-1, you may need to rearrange the components to provide a more pleasing appearance. Figure 14-12 shows the final appearance of the app.
You can resize the canvas so that it better matches your components. You can use a sizing arrow in the bottom-right corner for the purpose. Making your canvas fit the components gives your app a more finished feel.
TABLE 14-1 Configuring the Date Display App components
Component |
Property |
Setting |
Label portion of Edit Field (Text) |
Text |
Your Name |
Label portion of Date Picker |
Text |
Selected Date |
Date picker portion of Date Picker |
Value |
Current date |
Label portion of Drop Down |
Text |
Date Format |
Drop-down portion of Drop Down |
Items (each on their own line) |
Default yyyy-mmm-dd yyyy-mm-dd dd/mmm/yyyy dd mmm yyyy |
Button |
Text |
Show Messsage |
Label2 |
BackgroundColor |
White (you must select this value from the drop-down list, rather than simply typing it in the field) |
Label2 |
Text |
Blank |
FIGURE 14-12: The app looks nicer now and provides useful prompts.
Making the Interface Functional
If you were to run your app right now, you’d see an interesting interface, but nothing more. You need to add code to make the app do something. You have two approaches to adding code for your app. The easiest method is to allow MATLAB to manage most tasks for you. However, no matter what you do, you eventually end up in Code View, where you can type at least some minimalistic code. The following sections help you understand the underlying techniques for making your app functional.
Working with Code View
When you click Code View for your app, what you see is a specialized class, as shown in Figure 14-13. (See Chapter 13 for help in seeing how MATLAB classes work.) MATLAB automatically creates this class as you add components to the canvas and configure them. Every detail that you add to the app is part of the class code.
FIGURE 14-13: MATLAB wrote code while you created the app interface.
Notice that the createComponents() function declaration at the bottom of Figure 14-13 requires one argument, app. You use app much like you used obj in Chapter 13. It provides you with access to the application. Consequently, when you view the Edit Field (Text) component for entering a name, you see this code:
% Create YourNameEditFieldLabel
app.YourNameEditFieldLabel = uilabel(app.UIFigure);
app.YourNameEditFieldLabel.HorizontalAlignment = …
'right';
app.YourNameEditFieldLabel.Position = [21 142 65 22];
app.YourNameEditFieldLabel.Text = 'Your Name';
Every entry begins with app, which signifies that this piece of code interacts with the application. You don’t need to know what this code does unless you plan to modify it later. It’s actually a lot easier to use the Component Browser to change these settings and let MATLAB modify the underlying code for you. For now, all you really need to know is that there is a class in the background and that MATLAB manages it for you.
Creating a callback function
A callback function is one that registers itself to monitor and then respond to an event. For example, when the user clicks Show Message, a callback function will do something about the click. Every control in an app can have callback functions associated with it, but you need to provide callback functions only for essential tasks. The example application uses two callback functions: one for Date Format changes and another for Show Message clicks. Follow these steps to create a callback function:
1. Right-click the control that will need the callback, and choose the Callbacks menu from the context menu.
You see a list of callbacks associated with the control, as shown in Figure 14-14. In this case, you see the callbacks for Show Message. There is only one: ButtonPushedFcn. The Date Format control has two callbacks, but the example will use only the ValueChangedFcn callback.
FIGURE 14-14: Choose the callback function you want to add to the app.
2. Select the Add Function Name Callback entry you need.
You see a new callback function added to the code, as shown here for the ButtonPushedFcn, which is ShowMessageButtonPushed() for this specific instance.
% Callbacks that handle component events
methods (Access = private)
% Button pushed function: ShowMessageButton
function ShowMessageButtonPushed(app, event)
end
end
3. Type the code needed to make the callback work.
Remember that you access application features using the app object.
As previously mentioned, this example uses two callbacks. Listing 14-1 shows the code you need to add to the callbacks after you create them in bold.
LISTING 14-1 Creating Callbacks for the Example App
% Callbacks that handle component events
methods (Access = private)
% Button pushed function: ShowMessageButton
function ShowMessageButtonPushed(app, event)
name = app.YourNameEditField.Value;
formatOut = app.DateFormatDropDown.Value;
selDate = app.SelectedDateDatePicker.Value;
if strcmp(formatOut, 'Default')
formatOut = 'dd-mmm-yyyy'
end
date = datestr(selDate, formatOut);
msg = ['Hello ', name, ' it''s ', date, '!'];
app.Label.Text = msg;
end
% Value changed function: DateFormatDropDown
function DateFormatDropDownValueChanged(app, event)
value = app.DateFormatDropDown.Value;
if strcmp(value, 'Default')
value = 'dd-mmm-yyyy'
end
app.SelectedDateDatePicker.DisplayFormat = value;
end
end
The ShowMessageButtonPushed() code begins by obtaining all the required values from the various controls. It then ensures that formatOut contains a usable value in the form of a date format string. The next step is to convert the date into a date string using datestr(). Finally, the code creates a message, msg, and outputs it to app.Label.Text.
The DateFormatDropDownValueChanged() code has two purposes. First, it ensures that the selected date value is in a useful date format string form. It then assigns this value to app.SelectedDateDatePicker.DisplayFormat to modify the presentation on the form so that the user knows how the final date will look.
To remove a callback that you no longer need, select from the drop-down list for the event, such as ValueChangedFcn for a Date Picker, in the Callbacks tab of the Component Browser. You can then delete the associated code in Code View. Make sure to delete the entire function.
Running the App
You need to be sure to save your app before you run it. Even though MATLAB rarely freezes, you never know when a crashed system will ruin your day. Unfortunately, MATLAB won’t tell you that the app hasn’t been saved. It’s a good habit to click Save before you click Run. Saving your app will take a lot less time than recreating it.
To test your app, click Run. Type a name in the Your Name field, ensure that the Selected Date and Date Format fields are correct, and then click Show Message. Figure 14-15 shows a typical example of what the application might look like.
FIGURE 14-15: The final app provides a simple interface for displaying the date.
Packaging Your App
Packaging your app is a matter of using a wizard to answer some basic questions and then generating the .mlappinst file. The following steps give you a short overview of the process.
1. Click Package App in the File section of the Apps tab.
You see the wizard, shown in Figure 14-16.
FIGURE 14-16: Start the Package App wizard.
2. Click Add Main File.
You see an Add Files dialog box, where you select the DateDisplay.mlapp file.
3. Click Open.
You see the file added to the Main File list.
4. Fill in the details in the center section of the wizard.
As a minimum, you should provide a name for your app and your contact information, along with a summary of the app’s purpose.
5. Choose a folder in the Output Folder section.
6. Click Package.
After a few seconds, if there are no errors, you see a message: Packaging Complete. You can then click Open Output Folder to see the package for yourself.
As part of creating the package, MATLAB also creates a Date Display App.prj file. Open this file if you want to make changes to how you package your app.