Main Content

Deploying a Simulation App with Simulink Compiler

This example walks you through the workflow of creating a simulation app in App Designer and using Simulink® Compiler(TM ) to deploy it. Deploying an application allows you to share Simulink™ simulations in the form of an executable. The example explains the code that is used to build the app.

Open and Explore Model

In this example, we use the model of a mass spring damper system. The mass-spring-damper model consists of discrete mass nodes distributed throughout an object and interconnected via a network of springs and dampers. This model is well-suited for modeling object with complex material properties such as non-linearity and elasticity. In this example we use the mass spring damper system. The system is parameterized by mass (m), spring stiffness (k), damping (b) and the initial position (x0). The input to the system is the applied force.

To explore this model with different values of the tunable parameters, create the following model workspace variables:

  • Mass - m.

  • Spring stiffness - k.

  • Damping - b.

  • Initial position - x0.

open_system('MassSpringDamperModel');

Create the App in App Designer

Use the MATLAB App Designer to create an app to simulate the model with different parameter values and input signals. To learn more about how to create an app using the App Designer, see Create and Run a Simple App Using App Designer Use the MassSpringDamperApp.mlapp file to use the app.

MassSpringDamperApp

App Details

The main part for the app is the simulate button callback function. It has the following salient parts: setup the SimulationInput object, configure it for deployment, simulate, and plot the simulation results.

The functionality of the application to change and experiment with the tunable parameters is defined in the callback function SimulateButtonPushed. This callback function enables you to change, experiment and analyze different simulations by modifying the values in the app designer.

Callback Functions

This section explains the code written to create the app, MassSpringDamperApp. The code for the MassSpringDamperApp uses many callback functions. You can inspect the code by opening the MassSpringDamperApp,mlapp file in the App Designer. The createSimulationInput and modifyParameterDuringSim functions help set the values while also updating the simulation values in the app. We use the Simulink.SimulationInput object to set the variables to the model and use these variables to change the values and analyze the model.

Create the Simulink.SimulationInput Object in the createSimulationInput Function

In the following function, create a SimulationInput object, SimInp for the model MassSpringDamperModel. Use the setVariable method on the SimulationInput object to load the parameter values into the variables k, m, b, and x0. Now that we have assigned all the values to the variables and set the input signal, the Simulink.SimulationInput object is required to be configured for deployment. Use the simulink.compiler.configureForDeployment function of Simulink Compiler. This function handles all the settings required for the script to be compatible for deployment by setting the simulation mode to rapid accelerator, and by setting the parameter RapidAcceleratorUpToDateCheck to off.

function simInp = createSimulationInput(app)
% Create an empty SimulationInput object
simInp = Simulink.SimulationInput(app.modelName);

% Specify External Inputs function to provide the input force
% get the current simulation results and update plots while sim
% is running
simInp = simulink.compiler.setExternalInputsFcn(simInp, @app.setInputAndUpdateResults);

% Load the parameters values from the ui edit fields
simInp = simInp.setVariable('k',app.StiffnessUIC.Value, 'Workspace', 'MassSpringDamperModel');
simInp = simInp.setVariable('m',app.MassUIC.Value, 'Workspace', 'MassSpringDamperModel');
simInp = simInp.setVariable('b',app.DampingUIC.Value, 'Workspace', 'MassSpringDamperModel');
simInp = simInp.setVariable('x0',app.X0UIC.Value, 'Workspace', 'MassSpringDamperModel');

% Since sim will run forever, turn off (or limit) data logging
simInp = simInp.setModelParameter('StopTime','inf');

simInp = simulink.compiler.configureForDeployment(simInp);

% create a rand stream used to generate force input values
app.randStreamForForceInput = ...
    RandStream("mt19937ar", "Seed", app.RandStreamSeedSpinner.Value);

end % createSimulationInput
%
% *Modify Parameters During Simulation*
To allow modification of the parameters during the simulation, use the
function |modifyParameterDuringSim|. This function gets the current
simulation status and then if the simulation is running or paused,
enables you to modify the values for the simulation.
function modifyParamterDuringSim(app, prmName, prmValue)
ss = simulink.compiler.getSimulationStatus(app.modelName);
if (ss ~= slsim.SimulationStatus.Running && ...
        ss ~= slsim.SimulationStatus.Paused)
    return;
end
slv = Simulink.Simulation.Variable(prmName, prmValue);
simulink.compiler.modifyParameters(app.modelName, slv);
end % modifyParamterDuringSim
%
% *Simulate and Plot the Results*

Use the configured Simulink.SimulationInput object to run the simulation with the designed app. The addPoints function plots and traces the simulation results as the app is running.

function addPoints(app, hLine, time, data, style)
            time = reshape(time, 1, numel(time));
            data = reshape(data, 1, numel(data));
            timePoints = hLine.XData;
            dataPoints = hLine.YData;

            if isempty(timePoints)
                timePoints = time;
                dataPoints = data;
            else
                if isequal(style,'stair')
                    assert(timePoints(end) <= time(1));
                    if timePoints(end) < time(1)
                        timePoints = [timePoints time(1)];
                        dataPoints = [dataPoints dataPoints(end)];
                    end
                end
                idx = find(time >= timePoints(end));
                timePoints = [timePoints time(idx)];
                dataPoints = [dataPoints data(idx)];
            end

            % Limit the number of data points per line trace
            if numel(timePoints) > app.MaxPointsPerSignalSpinner.Value
                startIdx = numel(timePoints) - app.MaxPointsPerSignalSpinner.Value + 1;
                timePoints = timePoints(startIdx:end);
                dataPoints = dataPoints(startIdx:end);
            end
            set(hLine, 'XData',timePoints, 'YData',dataPoints);

            % Shift the axes to show the latest data
            xLim = get(hLine.Parent,'XLim');
            if (time(end) > xLim(2))
                tInc = time(end) - xLim(2);
                xLim = xLim+tInc;
                set(hLine.Parent,'XLim',xLim);
            end

        end % addPoints
%

Test Out the Application in App Designer

Before deploying the application, ensure that the app runs in the App Designer. Click the Simulate button on the app to verify that the application works by simulating the model for different values.

Compile Script for Deployment

To compile the app, use the mcc command, followed by the script name.

mcc -m MassSpringDamperApp.mlapp

Run the Deployed Application

Compile the deployable as follows:

1. Enter standaloneApplicationCompiler command in the for MATLAB™ Command Window to launch the Standalone Application Compiler app.

2. In the Main File section, add the file to be deployed, MassSpringDamperApp.mlapp.

3. Click Build and Package to create the standalone application and installer.

Install and Run Deployed Application

To run the deployed executable, you must install MATLAB™ Runtime that matches the version of MATLAB™ used to compile the application at the same update level or newer. The end user can run the generated installer to install the deployed application along with MATLAB™ Runtime. It is recommended to run the deployed application from the Windows Command Prompt. Running the deployed application from the command prompt also enables the script to print errors when something is wrong in the deployed application. These errors can help troubleshoot the problem. The MassSpringDamperApp.mlapp contains errordlg, and errordlg is not supported on Web Apps.