Share Data Within App Designer Apps - MATLAB & Simulink (original) (raw)

Main Content

Using properties is the best way to share data within an app because properties are accessible to all functions and callbacks in an app. All UI components are properties, so you can use this syntax to access and update UI components within your callbacks:

For example, these commands get and set the Value property of a gauge. In this case, the name of the gauge isPressureGauge.

x = app.PressureGauge.Value; % Get the gauge value app.PressureGauge.Value = 50; % Set the gauge value to 50

However, if you want to share an intermediate result, or data that multiple callbacks need to access, then define a public or private property to store your data. Public properties are accessible both inside and outside of the app, whereas private properties are only accessible inside of the app.

Define a Property

Code View provides a few different ways to create a property:

After you select an option to create a property, App Designer adds a property definition and a comment to a properties block.

properties (Access = public) Property % Description end

The properties block is editable, so you can change the name of the property and edit the comment to describe the property. For example, this property stores a value for average cost:

properties (Access = public) X % Average cost end

If your code needs to access a property value when the app starts, you can initialize its value in the properties block or in thestartupFcn callback.

properties (Access = public) X = 5; % Average cost end

To restrict the types of values that a property can store, associate a data type with the property in the property definition. For example, this code requires that values assigned to X must be of a type that is compatible withdouble, and any assigned values are stored as adouble.

properties (Access = public) X double % Average cost end

Access a Property

Once you define a property, you can access and set the property value anywhere in your app code by using the syntaxapp. PropertyName.

y = app.X % Get the value of X app.X = 5; % Set the value of X

Example: Share Plot Data and a Drop-Down List Selection

This app shows how to share data in a private property and a drop-down list. It has a private property called Z that stores plot data. The callback function for the edit field updates Z when the user changes the sample size. The callback function for the Update Plot button gets the value of Z and the colormap selection to update the plot.

See Also

Topics