App Designer provides a tutorial that guides you through the process of creating a
simple app containing a plot and a slider. The slider controls the amplitude of the
plotted function. You can create this app by running the tutorial, or you can follow the
tutorial steps listed here.
Tutorial Steps for Creating the App
App Designer has two views for creating an app: Design View
and Code View. Use Design View to create
UI components and interactively lay out your app. Use Code View
to program your app behavior. You can switch between the two views using the toggle
buttons in the upper right-corner of App Designer.
To create the simple plotting app, open a new app in App Designer and follow these
steps.
Step 1: Create an Axes Component
In Design View, create UI components and modify their
appearance interactively. The Component Library contains
all components, containers, and tools that you can add to your app
interactively. Add a component by dragging it from the Component
Library onto the app canvas. You can then change the appearance
of the component by setting properties in the Component
Browser, or by editing certain aspects of the component, such as
size and label text, directly on the canvas.
In your plotting app, create an axes component to display plotted data. Drag
an Axes component from the Component
Library onto the canvas.
Step 2: Create a Slider Component
Drag a Slider component from the Component
Library onto the canvas. Place it below the axes
component.
Step 3: Update the Slider Label
Replace the slider label text. Double-click the label and replace the word
Slider
with Amplitude
.
When you have finished laying out your app, the canvas in Design
View should look like this:
For more information about laying out apps, see Lay Out Apps in App Designer Design View.
Step 4: Navigate to Code View
Once you have laid out your app, write code to program the behavior of your
app. Click the Code View button above the canvas to edit
your app code.
When you add components to your app in Design View, App
Designer automatically generates code that executes when you run the app. This
code configures your app appearance to match what you see on the canvas. This
code is not editable and is displayed on a gray background. As part of this
generated code, App Designer creates some objects for you to use when
programming your app behavior.
-
The
app
object — This object stores all of the
data in your app, such as the UI components and any data you specify
using properties. All functions in your app require this object as
the first argument. This pattern enables you to have access to your
components and properties from within those functions. -
The component objects — Whenever you add a component in
Design View, App Designer stores the
component as an object named using the form
app
.ComponentName
.
You can view and modify the names of the components in your app
using the Component Browser. To access and
update component properties from within your app code, use the
pattern
app
.ComponentName
.Property
.
Step 5: Add a Slider Callback Function
Program your app behavior using callback functions. A
callback function is a function that executes when the app user performs a
specific interaction, such as adjusting the value of a slider.
In your plotting app, add a callback function that executes whenever the user
adjusts the slider value. Right-click app.AmplitudeSlider
in
the Component Browser. Then select > in the context menu.
When you add a callback to a component, App Designer creates a callback
function and places the cursor in the body of that function. App Designer
automatically passes the app
object as the first argument of
the callback function to enable access components and their properties. For
example, in the AmplitudeSliderValueChanged
function, App
Designer automatically generates a line of code to access the value of the slider.
For more information about programming app behavior using callback functions,
see Callbacks in App Designer.
Step 6: Plot Data
When you call a graphics function in App Designer, specify the target axes or
parent object as an argument to the function.
In your plotting app, update the plotted data in the axes whenever the app
user changes the slider value by specifying the name of the axes object in your
app, app.UIAxes
, as the first argument to the
plot
function. Add this code to the second line of the
AmplitudeSliderValueChanged
callback to plot the scaled
output of the peaks
function on the
axes.
plot(app.UIAxes,value*peaks)
For more information about displaying graphics in an app, see Display Graphics in App Designer.
Step 7: Update Axes Limits
To access and update component properties from within your app code, use the
pattern
app
.ComponentName
.Property
.
In your plotting app, change the limits of the y-axis by
setting the YLim
property of the app.UIAxes
object. Add this command to the third line of the
AmplitudeSliderValueChanged
callback:
app.UIAxes.YLim = [-1000 1000];
Step 8: Run the App
Click
Run to save and run the app. Adjust the value of the
slider to plot some data in the app.
After saving your changes, your app is available for running again in App
Designer or by typing its name (without the .mlapp
extension)
in the MATLAB® Command Window. When you run the app from the command prompt, the
file must be in the current folder or on the MATLAB path.
MATLAB is a powerful, high-level programming language. Matlab is widely used for designing systems by engineers and scientists and we all know that the best way to represent any idea is by using a simple but effective GUI. Matlab app builder provides you the power to build different apps, to represent your idea in a GUI-friendly manner.
In this article were going to learn how to create any app in Matlab App Designer.
Step 1: You can start working on the MATLAB APP Builder in two ways. Either go to Home>New>App.
Alternatively, for going to the Matlab app builder section, Select Apps from the Menubar, and then go to Design App.
Step 2: A new pop-up is opened. It provides a different layout for stating the app. It has also come examples for a better understanding.
Step 3: You can choose any App option to build a MATLAB app. There are mainly three layouts available on the go. These includes
- Blank App
- 2-Panel App with Auto-Reflow
- 3-Panel App with Auto-Reflow
Step 4: MATLAB consists of various components like:
- Components
- Customizing Components
Components are the pre-built shapes that are designed for particular tasks, and that could be imported to the design tab. In Matlab, the Component Library is situated in the leftmost part of the window.
For importing any component to your design right-click on the component and drag it to the design tab and drop it wherever you want to place it.
By using customizing components you can customize your components as per your requirements, using the Component browser. It is situated in the rightmost part of the App Builder Window. Using the Component Browser you can change information about the component, Font and Color, Interactivity with the user, Position of the component in the design view, CallBack Execution Controls, Parents/Child members, and Identifiers. It also contains the list of the component adopted in your app.
Let’s understand more about app-building by making a simple app that calculates both simple and compound interest. For working on this app, create a select a blank workbook. Now the workspace will be opened. You can design the app in the Design tab and code it in the Code tab.
Designing the app takes five edit test fields (numeric), three of them would be editable for principal, rate, and time, whereas two would be non-editable holding the value of Simple Interest and Compound Interest. You can also add a label for a better design view. Also import a button that does the whole calculation and shows the result.
Let’s move to the coding part now. For adding the functionality of the Calculate button, add a push-back function. You can add a push-back function by right click on the button and then going to callbacks and then clicking on add a push-back function.
Example:
Matlab
function
CalculateButtonPushed(app, event)
amount = app.PrincipalEditField.Value;
rate = app.RateEditField.Value/100;
time = app.TimeEditField.Value;
simple_interest = amount*rate*time;
app.SimpleInterestEditField.Value = simple_interest;
compounded_amount = amount * ((1+rate).^time);
compounded_interest = compounded_amount - amount;
app.CompoundInterestEditField.Value = compounded_interest;
end
Output:
Last Updated :
15 Mar, 2022
Like Article
Save Article
Разработайте приложения в интерактивном режиме с помощью App Designer
App Designer является интерактивной средой разработки для разработки размещения приложения и программирования его поведения. Это обеспечивает полностью интегрированную версию MATLAB® Редактор и большой набор интерактивных компонентов пользовательского интерфейса. Это также предлагает менеджеру по размещению сетки, чтобы организовать ваш пользовательский интерфейс и автоматические опции обратного течения, чтобы заставить ваше приложение обнаружить и ответить на изменения в размере экрана. Это позволяет вам распределить приложения путем упаковки их в файлы инсталлятора непосредственно от панели инструментов App Designer, или путем создавания автономного настольного приложения, или веб-приложение (требует MATLAB Compiler™).
Чтобы начать, смотрите, Создают и Запуск Простое приложение Используя App Designer или смотрят Getting Started with App Designer.
Функции
appdesigner |
Начальная страница Открытия App Designer или существующий файл приложения |
Темы
Сопутствующая информация
Рекомендуемые примеры
Introduction:
MATLAB App Designer is a drag and drops feature of MATLAB that lets you create professional apps without being an experienced software developer. Drag and drop visual components to layout your graphical user interface (GUI) design and use the integrated editor to program its behaviour quickly. In this blog, you will get to know the essential elements of the app designer. After going through the blog, you will be able to design a complex-looking yet simple app in MATLAB App Designer. The app that we will be creating is an Amplitude Modulation Analyzer.
Difference between App Designer and GUIDE:
App designer is the recommended environment for app development. MathWorks is no longer putting development effort into improving GUIDE and hasn’t for several years. Meanwhile, a significant development effort is going into improving App Designer. Existing GUIDE apps can run in MATLAB, but they are no longer editable. App Designer looks much better and is easier to use than GUIDE. As of R2017b, App Designer can do anything GUIDE can do. App designer also supports Rich Canvas Interactions, Embedded Code Editor, Rich Property Editors, App Metadata Management etc. For more details or an in-depth comparison, you can refer to this link.
Main features of App Designer:
- Beginner-friendly interface makes it easy for new users to explore it independently.
- Design the user interface as well as the code behaviour of the app.
- The generated codes are fully object-oriented.
- Availability of many instrumentation devices like knob, lam, led, switch.
Now that we know some of the advantages of MATLAB App Designer, let’s go through the interface of the app designer.
Starting with App Designer:
There are two ways to start the App Designer in MATLAB. These are:
- On the Home tab, go to ‘New’ and select ‘App’ from the drop-down menu.
Starting app designer by home tab
Starting app designer by command
Once the App Designer is launched, you should have the following screen in front of you.
App designer window
On the top side of the designer tab, you have the following options – New, Open, Save, App Details, Share, and Run.
Designer tab
The first three options are self-explanatory. ‘App Details’ option shows your app’s name, summary, and description.
App details window
All three options are editable. You are advised to fill in the summary and description of your app so that whenever you share your app with someone, they can quickly get an overview of the functioning of your app.
The next button is ‘Share’, which, as the name suggests, is used to share your app with someone else. The ‘Run’ button is used to run the app.
The second tab, named canvas, gives you alignment and resizing options. As of now, you can leave it as it is.
The component library contains sliders, buttons, axes, led, gauges, etc.
Component library
It is divided into four parts: Common, Containers, Figure Tools, and Instrumentation. You can refer to the MATLAB documentation for a complete and detailed list of all the available components.
Designing your first app:
To start designing your app, you should first figure out what components you need. For example, if you need to show graphs in your app, you might need the Axes and Slider components. Also, have a rough idea in your mind of an interface that you want for your app. In this blog, we are creating a simple Amplitude Modulation App. We will start with dragging the Axes component on the design sheet.
Dragging axes component to Design View
In the app, I want to show three graphs for the message signal, carrier signal, and the modulated result respectively; therefore, I will have to set three axes on the design sheet.
All axes component in Design View
As you keep dragging specific components in the sheet, you might have noticed that new entries automatically appear in the component browser on the window’s right side. You can also edit certain properties by selecting the specific component and modifying it in the properties section below.
Component Browser and Properties
We will change the title, x, and y-axis only for now. You can also double-click on the text to edit it.
Labeling the axes
Now I want to give some input to my app. Since the information needs to be numeric, I have to use Edit Field (Numeric) component, Slider component, or Knob component. I will be using the first two components mentioned earlier, so let’s drag them to our design sheet.
Complete interface of app
As you can see, I have used four numeric fields and one slider component. I have already changed the labels of all the added components. Vm and Vc fields will be used to get the voltage or amplitude of the message and carrier signal. Similarly, Fm and Fc will be used to get the frequency of the message and carrier signal. Let’s add additional labels to them by dragging the Label component.
Adding labels
I will change the labels to ‘Voltage’ and ‘Frequency’, respectively. You should get the following UI in your design view if you have been following along until now.
Final UI of app
For now, our work in the design view is completed. Click on the Code View to switch to the coding part of the App Designer.
Opening code view
Code View of app
You will notice specific new options have come out while some things have changed. Let’s quickly glance over the new stuff. The first thing is the Editor tab on the top. It has some essential elements in the insert part. These are Callback, Function, Property, and App Input Arguments.
Editor tab in code view
A callback is a function that executes when a user interacts with a UI component in your app. We use callbacks to program the behaviour of our app. The function creates either a public function or a private function. Property is used to share data within an app. It is also of two types: public and private. App Input Arguments are used to bring in input arguments.
Callbacks, functions, and properties are accessible from the left side of the window under Code Browser. Below that, you can see App Layout, which shows a preview of your app. The right-side accessibility options are the same as before.
Code Browser and App Layout
Adding interactivity to the app components:
Now let’s add some callbacks to our app so that the added components can respond to the user input. I will be sowing the more straightforward method of adding callbacks. It would be best to have a rough idea of the components for which you want the callbacks. For example, I want to take voltage input and frequency input in my app. The moment I get the frequency input, I want to display their graphs in the axes. Therefore, I will be adding callbacks for the Fc and Fm fields.
In the component browser in the code view, select the entry having the name ‘FmEditField’. Right-click on it and go to callbacks.
Adding the first callback
Adding the first callback
After clicking on add callback button, your cursor will be placed in the following section.
Callback function
As you can see, you have created a private callback function for your app for the Fm Edit Field component. The value variable takes whatever value is being provided by the user.
Add the following lines of code in this function.
% Value changed function: fmEditField
function fmEditFieldValueChanged(app, event)
fm = app.fmEditField.Value;
vm = app.VmEditField.Value;
Ta=1/fm;
t=0:Ta/999:6*Ta;
ym=vm*sin(2*pi*fm*t);
plot(app.UIAxes, ym, ‘r’)
end
Here, we are also reading the value of the Vm edit field, but there is no response for that in the app. The moment we get the frequency or Fm, we plot the graph. So you can say that the Fm edit filed is creating some response in the app. Add another callback function for the Fc edit field by following the above steps. After adding the callback, write the following lines of code in the function.
% Value changed function: fcEditField
function fcEditFieldValueChanged(app, event)
fm = app.fmEditField.Value;
fc = app.fcEditField.Value;
vc = app.VcEditField.Value;
Ta=1/fm;
t=0:Ta/999:6*Ta;
yc=vc*sin(2*pi*fc*t);% Eqation of carrier signal
plot(app.UIAxes2, yc)
end
We are doing the same thing here, i.e., as soon as we have the value of Vc and Fc, we plot a graph for the carrier signal.
Now add a callback function for the slider component and write the following lines of code.
% Value changed function: ModulationSlider
function ModulationSliderValueChanged(app, event)
m = app.ModulationSlider.Value;
m = 0.01*m;
vc = app.VcEditField.Value;
fm = app.fmEditField.Value;
fc = app.fcEditField.Value;
Ta=1/fm;
t=0:Ta/999:6*Ta;
y = vc*(1+m*sin(2*pi*fm*t)).*sin(2*pi*fc*t);
plot(app.UIAxes3, y, ‘g’)
end
Running our app
I have given the app a name and tweaked the plot colours. You can do the same in the design view in the app properties.
Let’s give some sample input and check whether the app is working or not.
Input:
Vm – 5
Vc – 5
Fm – 500
Fc – 2000
Modulation % – 20
Output result in app
Conclusion:
We have successfully created an Amplitude Modulation Analyzer as an app using MATLAB App Designer. Why did we even bother to do our work with an app? Well, the answer lies in our results. We can create an incredible looking impact with the help of apps. It also decreases the amount of work needed to get the output or outcome. Even a non-technical person can use the app to do their job.
Explore more:
We have covered many more topics using the MATLAB App Designer. Some of our most sought-after works are:
IPL with MATLAB
Perform programming with the Indian Premier League in MATLAB and visualize the progress of each team as it’s happening with the graphical power of MATLAB & App Designer.
Blood Cell Counter with MATLAB
In this webinar, you will learn the concepts of image segmentation for analyzing and counting red and white blood cells in MATLAB App Designer. This webinar is a must-watch if you want to create a project based on RBC & WBC Segmentation.
Fitness Tracker with MATLAB
In this webinar, you will learn about your fitness and health and the importance of the parameters like BMI, WHR, WHtR, etc. You will be able to track your fitness within MATLAB with our Application.
Get instant access to the code, model, or application of the video or article you found helpful! Simply purchase the specific title, if available, and receive the download link right away! #MATLABHelper #CodeMadeEasy
Ready to take your MATLAB skills to the next level? Look no further! At MATLAB Helper, we’ve got you covered. From free community support to expert help and training, we’ve got all the resources you need to become a pro in no time. If you have any questions or queries, don’t hesitate to reach out to us. Simply post a comment below or send us an email at [email protected].
And don’t forget to connect with us on LinkedIn, Facebook, and Subscribe to our YouTube Channel! We’re always sharing helpful tips and updates, so you can stay up-to-date on everything related to MATLAB. Plus, if you spot any bugs or errors on our website, just let us know and we’ll make sure to fix it ASAP.
Ready to get started? Book your expert help with Research Assistance plan today and get personalized assistance tailored to your needs. Or, if you’re looking for more comprehensive training, join one of our training modules and get hands-on experience with the latest techniques and technologies. The choice is yours – start learning and growing with MATLAB Helper today!
Education is our future. MATLAB is our feature. Happy MATLABing!
Typing the command appdesigner in the Command Window will bring up the App Designer. Fig. 1 shows the App Designer; in the middle is the blank layout under “Design View.” The Component Library on the left shows the icons of the components that can be created. On the right are the Component Browser and Component Properties Windows. In the Component Browser, the default name for the blank figure, app. UIFigure, can be seen.
>> appdesigner
Fig. 2 shows the remainder of the Component Library, including the Container and Instrumentation components. Clicking on “Code View” instead of “Design View” shows the code that has been created for the blank app. App Designer creates a class named Appl that is derived from a MATLAB apps superclass called matlab.apps.AppBase. The properties will consist of all of the components; for now, there is just one property, which is the UI Figure Window. There are also two private methods blocks and one public methods block.
The methods are used for all of the app functions, including eventually callback functions. For now, with just a blank UI Figure Window, the public methods include the constructor function Appl, and a function delete that deletes the figure when the app is deleted. The constructor calls a private function createComponents, which creates a UI Figure using the uifigure function. It then uses the dot notation to set properties for the app. UIFigure, including its Name and Position. Note that the dot notation is used twice here, as in app.UIFigure. Name.
The function startupFcn executes when components are created. It is called by a function in the constructor. Within the Code View, most of the window is grey, which means that the code cannot be modified. However, within the startupFcn function there is a white box, which means that code can be inserted in that function. Fig. 3 shows the startupFcn function in Code View.
We have seen the code that is generated with just a blank canvas. In the Design View of the App Designer environment, components can be dragged from the Component Library onto the blank layout. When this is done, the code will be updated to create a new property for each component, and to initialize some of its properties (for example, the Position property will be based on the location to which the component was dragged). Properties can then be modified in the Component Properties Window to the right of the layout.
For example, dragging a Label (generically named ‘Label’!) into the design area causes the Design View to look like Fig. 4.
Clicking on the label itself in the Design View will change “Component Properties” to “Label Properties.” Properties such as the text on the label, its justification, font name, font size, and so forth can then be modified from the Label Properties window. Each of these will modify the code that is created.
Assuming that no properties have been modified, and there is just a generic label in the layout as shown in Fig. 4, most of the code remains the same as with just a blank UI Figure Window. Choosing Code View will show that the class App 1 now has a new property Label, and the createComponents method creates a Label using the uilabel function and gives it a Position. The added code is shown in bold here (not in App Designer itself).
classdef Appl < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access= public)
UIFigure matlab.ui.Figure % UI Figure
Label matlab.ui.control.Label % Label
end
% Create UIFigure
function createComponents (app)
app.UIFigure = uifigure;
app.UIFigure.Position = [100 100 640 480];
app.UIFigure.Name = 'UI Figure' ;
setAutoResize(app, app.UIFigure, true)
% Create Label
app.Label = uilabel (app. UIFigure);
app.Label.Position = [421 431 30 151];
end
end
Modifying a property, such as changing the text of the label in the Label Properties window to be “Hello” instead of “Label” will modify the code in
createComponents to:
% Create Label
app.Label = uilabel(app.UIFigure);
app.Label.Position = [421 43130151;
app.Label.Text = 'Hello';
It is also possible programmatically to modify properties such as app. Label. Text in the startupFcn function, but it is preferable and easier to do this from the Design View.
To run the app, click on the green Run arrow. This brings up a dialog box that asks for the name of the file that will be created; the default name that shows is “App 1.mlapp.” Changing the name to “HelloLabel.mlapp” will create a file with this name and bring up a UI Figure Window. The upper right portion of this is shown in Fig. 5.
Note that the App Designer creates one file with the extension ‘.mlapp,’ unlike GUIDE, which creates two files: a .m file and a .fig file.
While this example shows the basics of App Designer and the object-based code that it creates, it did not involve any callbacks.
UI Figure Functions
Traditional GUis create different types of objects by specifying the Style property in the uicontrol function. For example, a slider is created with uicontrol(‘Style’, ‘slider’). By contrast, App Designer uses separate functions to create the different component types; for example, a slider is created with the uislider function. In the previous section, we saw two of these functions: uifigure, which creates the UI Figure Window, and uilabel, which creates a static text box.
All of these functions can be called directly from the Command Window or from any script or function. For example, the following code will bring up the UI Figure Window shown in Fig. 6.
>> uif = uifigure; >> uif .Name= 'Simple UI Fig Slider'; >> uislid = uislider(uif);
By creating a UI Figure Window first, and then passing its handle to the uislider function, the slider is put inside that UI Figure Window (otherwise, a new UI Figure Window would be created for the slider). The Value property of the slider can be inspected, e.g.,
>> uislid.Value
ans=
0
Of course, to do anything with the value of the slider would require more complicated code with callback functions. For sliders, there are two:
- ValueChangedFcn‘: executes when the slider value has been changed
- ValueChangingFcn‘: executes as the slider is being moved
For example, the function uislideruilabel creates a UI Figure Window with a slider and a label. When the slider has been moved, the ValueChangedFcn‘ callback is called, which puts the value of the slider in the label as seen in Fig. 13.35. Many of the concepts here are similar to those used in GUI callbacks.
The function uislideruilabel is a function that has a nested callback function, whatslid. Since the whatslid function is nested, the variable scope is such that the variables uilab and uislid can be used within the callback function without passing them. The callback function has two input arguments representing the source of the callback (in this case uislid) and the eventdata, just like GUI callback functions.
function uislideruilabel uif= uifigure; uif.Name = 'UI Fig Slider with Callback' ; uislid = uislider (uif) ; uilab = uilabel (uif , ' Position ', [150 200 30 15] ); uilab.Text = 'O' ; uislid.ValueChangedFcn= @whatslid; function whatslid (source, event) uilab.Text = num2str(round(uislid.Value)); end end
The list of UI functions that create object components can be found in the App Designer documentation. The documentation for each function describes the properties that can be used for each, including all of the possible callback functions.