Matlab Example Programrubackup



By David Garrison, MathWorks

  1. Matlab Example Programrubackup Python
  2. Matlab Example Programrubackup Method

An app is a self-contained MATLAB® program, with a GUI, that automates a task or calculation. All the operations required to complete the task—getting data into the app, performing calculations on that data, and getting results—are performed within the app.

MATLAB MATLAB is a software package for doing numerical computation. It was originally designed for solving linear algebra type problems using matrices. It’s name is derived from MATrix LABoratory. MATLAB has since been expanded and now has built-in functions for solving problems requiring data analysis, signal. The example function computes the angles of a right triangle, and you create a script-based unit test to test the function. Create rightTri Function to Test. Create this function in a file, rightTri.m, in your current MATLAB® folder. This function takes lengths of two sides of a triangle as input and returns the three angles of the.

Starting in R2012b, you can package your own apps to share with other MATLAB users. You can also download apps written by others from the MATLAB Central File Exchange or other sources and install them in the apps gallery (Figure 1).

Figure 1. The MATLAB apps gallery with a custom app installed in 'My Apps.'

Because an app has a GUI that a user interacts with, writing an app differs in certain respects from writing other MATLAB programs. When you write an app, you are creating an event-driven program. Once your app is on the screen, it typically remains idle until a user causes an event by interacting with the app—for instance, by entering text or clicking a button. In response to that action, a callback function is executed. That callback function, provided by the app's author, executes some code in response to the event that triggered it. For example, clicking a Run button might execute a callback function that performs some engineering calculations and updates a plot shown in the GUI.

In event-driven programming, each event callback is a short function that must obtain the data that it needs to do its job, update the app as necessary, and store its results where other callbacks can access them. The underlying app is essentially a collection of small functions working together to accomplish the larger task. When writing an event-driven program, you face the issues of writing the callbacks for the controls in your app and managing the information to be shared among these callbacks.

MATLAB supports two approaches to writing apps. You can:

  • Write the code from scratch
  • Use GUIDE, the MATLAB Graphical User Interface Design Environment

Most users find it easier to use GUIDE to graphically lay out the GUI and generate an event-driven framework for the app. Some, however, prefer the extra control they get from authoring apps from scratch. This article describes a method for writing apps from scratch using object-oriented programming. We've found this method to be an efficient way to create robust user interfaces.

An object manages a collection of related functions and the data they share. Objects are particularly useful for writing event-driven programs. Unfortunately, however, many programmers avoid using objects, either because they think they are too complicated or because they find the task of learning object-oriented programming daunting.

Example

Don't worry. You do not need to become an expert in object-oriented programming to use objects to build an app. You just need to understand a few basic concepts.

When you create an object, you need to define two things: its list of Properties—the data stored within the object—and its methods—the functions that operate on the data stored in the properties of the object.

Let's look at a simple stock ticker app that updates a graph of stock prices over time for a given ticker symbol (Figure 2).

Figure 2. Simple stock ticker app.

The simpleStockTicker MATLAB program creates the object that implements the app.

The first line of the program tells MATLAB that you are defining a new class.

The classdef keyword defines a new type of object (a “class”). The name of the class, simpleStockTicker, must match the name of the MATLAB file. The last part of the line, < handle, instructs MATLAB not to make copies of this object. All your apps will start like this; only the class name (simpleStockTicker in our example) will change.

The properties section comes next. The properties section is defined by the properties...end syntax. It is where you define the data that will be used by the object.

This class uses two groups of properties. The first five properties store the handles to the visual components of the user interface—the figure, the axis, the line plotted for the prices, the 'Symbol' label, and the edit box where you can type the ticker symbol name. The last four properties store data that is used to obtain and plot the stock prices. These properties can be used by any method of the class.

Using properties helps address a common problem in authoring apps: where to store data that needs to be shared by different parts of the app. Traditionally, the most common approaches have been to use guidata or global variables to store shared data, but these approaches have limitations. It can be difficult to keep guidata up-to-date and to access that data when the app needs it. Shared data stored as properties is easy to define and easy to access from anywhere in the app.

After defining the object's properties, you define its methods using the methods...end syntax. The first method, the constructor, is used to create the object. The name of the constructor is always the same as the name of the class.

Note that the constructor must have one output variable. The output variable is used to refer to the object created by the constructor function. You can give it any name you like. The class in our example uses the name app. The output variable is special in that it is used inside the class definition file to refer to the object's properties and methods. For example, you would refer to the object's NumValues property by using the syntax app.NumValues. All methods of the class are defined with this special variable as their first argument.

In our example, the constructor function performs three tasks: It creates all the visual objects in the user interface, initializes the prices to be plotted, and creates a Timer object that will update periodically to get the latest stock price. The update rate is controlled by the app.TimerUpdateRate property of the class.

The next three methods in this class are the callbacks. Below is the CloseRequestFcn callback for the figure window. It is called when the figure is closed. It looks like other callback functions you may have written, with one exception: The variable app must be inserted at the beginning of the argument list for the method.

Note that a class definition file can contain other methods that are not callbacks—for example, the getQuote method. This method is called by other methods of the class.

Programmers often promote the advantages of object-oriented programming over traditional functional programming. They cite encapsulation, abstraction, and polymorphism as reasons for using an object-oriented approach. While these are all useful concepts, you do not need to understand them to write your app as a MATLAB class. The most important reason for using a class to create your app is that the class provides a useful way to manage data shared by different parts of your app. The properties of the object hold all the data that needs to be shared among the methods (callbacks) of your app. You no longer need to worry about using guidata or global variables because now all the data is stored in the properties of the class.

For more examples of apps built using a class, see the Learn More section.

Published 2012 - 92062v00

Products Used

Learn More

Matlab Example Programrubackup

View Articles for Related Capabilities

This example shows how to write a script that tests a function that you create. The example function computes the angles of a right triangle, and you create a script-based unit test to test the function.

Create rightTri Function to Test

Matlab

Create this function in a file, rightTri.m, in your current MATLAB® folder. This function takes lengths of two sides of a triangle as input and returns the three angles of the corresponding right triangle. The input sides are the two shorter edges of the triangle, not the hypotenuse.

Create Test Script

In your working folder, create a new script, rightTriTest.m. Each unit test checks a different output of the rightTri function. A test script must adhere to the following conventions:

  • The name of the test file must start or end with the word 'test', which is case-insensitive. If the file name does not start or end with the word 'test', the tests in the file might be ignored in certain cases.

  • Place each unit test into a separate section of the script file. Each section begins with two percent signs (%%), and the text that follows on the same line becomes the name of the test element. If no text follows the %%, MATLAB assigns a name to the test. If MATLAB encounters a test failure, it still runs remaining tests.

  • In a test script, the shared variable section consists of any code that appears before the first explicit code section (the first line beginning with %%). Tests share the variables that you define in this section. Within a test, you can modify the values of these variables. However, in subsequent tests, the value is reset to the value defined in the shared variables section.

  • In the shared variables section (first code section), define any preconditions necessary for your tests. If the inputs or outputs do not meet this precondition, MATLAB does not run any of the tests. MATLAB marks the tests as failed and incomplete.

  • When a script is run as a test, variables defined in one test are not accessible within other tests unless they are defined in the shared variables section (first code section). Similarly, variables defined in other workspaces are not accessible to the tests.

  • If the script file does not include any code sections, MATLAB generates a single test element from the full contents of the script file. The name of the test element is the same as the script file name. In this case, if MATLAB encounters a failed test, it halts execution of the entire script.

In rightTriTest.m, write four tests to test the output of rightTri. Use the assert function to test the different conditions. In the shared variables section, define four triangle geometries and define a precondition that the rightTri function returns a right triangle.

Test 1 tests the summation of the triangle angles. If the summation is not equal to 180 degrees, assert throws an error.

Test 2 tests that if two sides are equal, the corresponding angles are equal. If the non-right angles are not both equal to 45 degrees, the assert function throws an error.

Test 3 tests that if the triangle sides are 1 and sqrt(3), the angles are 30, 60, and 90 degrees. If this condition is not true, assert throws an error.

Test 4 tests the small-angle approximation. The small-angle approximation states that for small angles the sine of the angle in radians is approximately equal to the angle. If it is not true, assert throws an error.

Run Tests

Execute the runtests function to run the four tests in rightTriTest.m. The runtests function executes each test in each code section individually. If Test 1 fails, MATLAB still runs the remaining tests. If you execute rightTriTest as a script instead of by using runtests, MATLAB halts execution of the entire script if it encounters a failed assertion. Additionally, when you run tests using the runtests function, MATLAB provides informative test diagnostics.

The test for the 30-60-90 triangle and the test for the small-angle approximation fail in the comparison of floating-point numbers. Typically, when you compare floating-point values, you specify a tolerance for the comparison. In Test 3 and Test 4, MATLAB throws an error at the failed assertion and does not complete the test. Therefore, the test is marked as both Failed and Incomplete.

To provide diagnostic information (Error Details) that is more informative than 'Assertion failed' (Test 3), consider passing a message to the assert function (as in Test 4). Or you can also consider using function-based unit tests.

Revise Test to Use Tolerance

Save rightTriTest.m as rightTriTolTest.m, and revise Test 3 and Test 4 to use a tolerance. In Test 3 and Test 4, instead of asserting that the angles are equal to an expected value, assert that the difference between the actual and expected values is less than or equal to a specified tolerance. Define the tolerance in the shared variables section of the test script so it is accessible to both tests.

For script-based unit tests, manually verify that the difference between two values is less than a specified tolerance. If instead you write a function-based unit test, you can access built-in constraints to specify a tolerance when comparing floating-point values.

Rerun the tests.

All the tests pass.

Matlab Example Programrubackup Python

Create a table of test results.

Matlab Example Programrubackup Method

See Also

assert | runtests

Related Topics