Main Content

Accelerate, Refine, and Test Hybrid Dynamic System on Host Computer by Using RSim System Target File

After you create a model, you can use the rapid simulation (RSim) system target file to characterize model behavior. The executable program that results from the build process is for non-real-time execution on your development computer. The executable program is highly optimized for simulating models of hybrid dynamic systems, including models that use variable-step solvers and zero-crossing detection. The speed of the generated code makes the RSim system target file ideal for building programs for batch or Monte Carlo simulations.

About Rapid Simulation

Use the RSim target to generate an executable that runs fast, standalone simulations. You can repeat simulations with varying data sets, interactively or programmatically with scripts, without rebuilding the model. This can accelerate the characterization and tuning of model behavior and code generation testing.

Using command-line options:

  • Define parameter values and input signals in one or more MAT-files that you can load and reload at the start of simulations without rebuilding your model.

  • Redirect logging data to one or more MAT-files that you can then analyze and compare.

  • Control simulation time.

  • Specify external mode options.

Note

To run an RSim executable, configure your computer to run MATLAB® and have the MATLAB and Simulink® installation folders accessible. To deploy a standalone host executable ( i.e., without MATLAB and Simulink installed), consider using the Host-Based Shared Library target (ert_shrlib)."

Rapid Simulation Advantage

The advantage that you gain from rapid simulation varies. Larger simulations achieve speed improvements of up to 10 times faster than standard Simulink simulations. Some models might not show noticeable improvement in simulation speed. To determine the speed difference for your model, time your standard Simulink simulation and compare the results with a rapid simulation. In addition, test the model simulation in Rapid Accelerator simulation mode.

General Rapid Simulation Workflow

Like other stages of Model-Based Design, characterization and tuning of model behavior is an iterative process, as shown in the general workflow diagram in the figure. Tasks in the workflow are:

Identify Rapid Simulation Requirements

The first step to setting up a rapid simulation is to identify your simulation requirements.

Question...For More Information, See...
How long do you want simulations to run? Configure and Build Model for Rapid Simulation
Are there solver requirements? Do you expect to use the same solver for which the model is configured for your rapid simulations?Configure and Build Model for Rapid Simulation
Do your rapid simulations need to accommodate flexible custom code interfacing? Or, do your simulations need to retain storage class settings?Configure and Build Model for Rapid Simulation
Will you be running simulations with multiple data sets?Set Up Rapid Simulation Input Data
Will the input data consist of global parameters, signals, or both?Set Up Rapid Simulation Input Data
What type of source blocks provide input data to the model — From File, Inport, From Workspace? Set Up Rapid Simulation Input Data
Will the model's parameter vector (model_P) be used as input data?Create a MAT-File That Includes a Model Parameter Structure
What is the data type of the input parameters and signals?Set Up Rapid Simulation Input Data
Will the source data consist of one variable or multiple variables?Set Up Rapid Simulation Input Data
Does the input data include tunable parameters?Create a MAT-File That Includes a Model Parameter Structure
Do you need to gain access to tunable parameter information — model checksum and parameter data types, identifiers, and complexity?Create a MAT-File That Includes a Model Parameter Structure
Will you have a need to vary the simulation stop time for simulation runs?Configure and Build Model for Rapid Simulation andOverride a Model Simulation Stop Time
Do you want to set a time limit for the simulation? Consider setting a time limit if your model experiences frequent zero crossings and has a small minor step size.Set a Clock Time Limit for a Rapid Simulation
Do you need to preserve the output of each simulation run? Specify a New Output File Name for a Simulation and Specify New Output File Names for To File Blocks
Do you expect to run the simulations interactively or in batch mode?Scripts for Batch and Monte Carlo Simulations

Configure Inports to Provide Simulation Source Data

You can use Inport blocks as a source of input data for rapid simulations. To do so, configure the blocks so that they can import data from external MAT-files. By default, the Inport block inherits parameter settings from downstream blocks. In most cases, to import data from an external MAT-file, you must explicitly set the following block parameters to match the source data in the MAT-file.

  • Main > Interpolate data

  • Signal Attributes > Port dimensions

  • Signal Attributes > Data type

  • Signal Attributes > Signal type

If you do not have control over the model content, you might need to modify the data in the MAT-file to conform to what the model expects for input. Input data characteristics and specifications of the Inport block that receives the data must match.

For details on adjusting these parameters and on creating a MAT-file for use with an Inport block, see Create a MAT-File for an Inport Block. For descriptions of the preceding block parameters, see the block description of Inport.

Configure and Build Model for Rapid Simulation

After you identify your rapid simulation requirements, configure the model for rapid simulation.

  1. Set model configuration parameter System target file to rsim.tlc (Rapid Simulation Target).

  2. Click RSim Target to view the RSim Target pane.

  3. Set the RSim target configuration parameters for your rapid simulation requirements.

    If You Want to... Then...
    Generate code that allows the RSim executable to load parameters from a MAT-fileSelect Enable RSim executable to load parameters from a MAT-file (default).
    Let the target choose a solver based on the solver already configured for the model

    Set Solver selection to auto (default). The code generator uses a built-in solver if a fixed-step solver is specified on the Solver pane or calls the Simulink solver module (a shared library) if a variable-step solver is specified.

    Explicitly instruct the target to use a fixed-step solverSet Solver selection to Use fixed-step solvers. In the Configuration Parameters dialog box, on the Solver pane, specify a fixed-step solver.
    Explicitly instruct the target to use a variable-step solver

    Set Solver selection to Use Simulink solver module. In the Configuration Parameters dialog box, on the Solver pane, specify a variable-step solver.

    Force storage classes to Auto for flexible custom code interfacingSelect Force storage classes to AUTO (default).
    Retain storage class settings, such as ExportedGlobal or ImportedExtern, due to application requirementsClear Force storage classes to AUTO.
  4. Set up data import and export options. On the Data Import/Export pane, in the Save to Workspace section, select the Time, States, Outputs, and Final States parameters, as they apply. By default, the code generator saves simulation logging results to a file named model.mat. For more information, see Export Simulation Data.

  5. If you are using external mode communication, set up the interface, using the Code Generation > Interface pane. See External Mode Simulations for Parameter Tuning and Signal Monitoring for details.

  6. Press Ctrl+B. The code generator builds a highly optimized executable program that you can run on your development computer with varying data, without rebuilding.

    For more information on compilers that are compatible with the Simulink Coder™ product, see Select and Configure C or C++ Compiler and Template Makefiles and Make Options .

Set Up Rapid Simulation Input Data

About Rapid Simulation Data Setup

The format and setup of input data for a rapid simulation depends on your requirements.

If the Input Data Source Is...Then...
The model's global parameter vector (model_P)Use the rsimgetrtp function to get the vector content and then save it to a MAT-file.
The model's global parameter vector and you want a mapping between the vector and tunable parametersCall the rsimgetrtp function to get the global parameter structure and then save it to a MAT-file.
Provided by a From File blockCreate a MAT-file that a From File block can read.
Provided by an Inport blockCreate a MAT-file that adheres to one of the three data file formats that the Inport block can read.
Provided by a From Workspace blockCreate structure variables in the MATLAB workspace.

The RSim target requires that MAT-files used as input for From File and Inport blocks contain data. The grt target inserts MAT-file data directly into the generated code, which is then compiled and linked as an executable. In contrast, RSim allows you to replace data sets for each successive simulation. A MAT-file containing From File or Inport block data must be present if a From File block or Inport block exists in your model.

Create a MAT-File That Includes a Model Parameter Structure

To create a MAT-file that includes a model global parameter structure (model_P),

  1. Get the structure by calling the function rsimgetrtp.

  2. Save the parameter structure to a MAT-file.

If you want to run simulations over varying data sets, consider converting the parameter structure to a cell array and saving the parameter variations to a single MAT-file.

Get the Parameter Structure for a Model.  Get the global parameter structure (model_P) for a model by calling the function rsimgetrtp.

param_struct = rsimgetrtp('model')
ArgumentDescription
modelThe model for which you are running the rapid simulations.

The rsimgetrtp function forces an update diagram action for the specified model and returns a structure that contains the following fields.

FieldDescription
modelChecksumA four-element vector that encodes the structure of the model. The code generator uses the checksum to check whether the structure of the model has changed since the RSim executable was generated. If you delete or add a block, and then generate a new model_P vector, the new checksum does not match the original checksum anymore. The RSim executable detects this incompatibility in parameter vectors and exits to avoid returning incorrect simulation results. If the model structure changes, you must regenerate the code for the model.
parametersA structure that contains the model's global parameters.

The parameter structure contains the following information.

FieldDescription
dataTypeNameThe name of the parameter data type, for example, double
dataTypeIDInternal data type identifier used by the code generator
complexThe value 0 if real; 1 if complex
dtTransIdxInternal data index used by the code generator
valuesA vector of the parameter values associated with this structure
mapThis field contains the mapping information that correlates the 'values' to the tunable parameters of the model. This mapping information, in conjunction with rsimsetrtpparam, is useful for creating subsequent rtP structures without compiling the block diagram.

The code generator reports a tunable fixed-point parameter according to its stored value. For example, an sfix(16) parameter value of 1.4 with a scaling of 2^-8 has a value of 358 as an int16.

In the following example, rsimgetrtp returns the parameter structure for the example model rtwdemo_rsimtf to param_struct.

param_struct = rsimgetrtp('rtwdemo_rsimtf')
param_struct = 

    modelChecksum: [1.7165e+009 3.0726e+009 2.6061e+009 2.3064e+009]
       parameters: [1x1 struct]

Save the Parameter Structure to a MAT-File.  After you issue a call to rsimgetrtp, save the return value of the function call to a MAT-file. Using a command-line option, you can then specify that MAT-file as input for rapid simulations.

The following example saves the parameter structure returned for rtwdemo_rsimtf to the MAT-file myrsimdemo.mat.

save myrsimdemo.mat param_struct;

For information on using command-line options to specify required files, see Run Rapid Simulations.

Convert the Parameter Structure for Running Simulations on Varying Data Sets.  To use rapid simulations to test changes to specific parameters, you can convert the model parameter structure to a cell array. You can then access a specific parameter set by using the @ operator to specify the index for a specific parameter set in the file.

To convert the structure to a cell array:

  1. Use the function rsimgetrtp to get a structure containing parameter information for the example model rtwdemo_rsimtf. Store the structure in a variable param_struct.

    param_struct = rsimgetrtp('rtwdemo_rsimtf');
    

    The parameters field of the structure is a substructure that contains parameter information. The values field of the parameters substructure contains the numeric values of the parameters that you can tune during execution of the simulation code.

  2. Use the function rsimsetrtpparam to expand the structure so that it contains more parameter sets. In this case, create two more parameter sets (for a total of three sets).

    param_struct = rsimsetrtpparam(param_struct,3);

    The function converts the parameters field to a cell array with three elements. Each element contains information for a single parameter set. By default, the function creates the second and third elements of the cell array by copying the first element. Therefore, all of the parameter sets use the same parameter values.

  3. Specify new values for the parameters in the second and third parameter sets.

    param_struct.parameters{2}.values = [-150 -5000 0 4950];
    param_struct.parameters{3}.values = [-170 -5500 0 5100];
  4. Save the structure containing the parameter set information to a MAT-file.

    save rtwdemo_rsimtf.mat param_struct;

Alternatively, you can modify the block parameters in the model, and use rsimgetrtp to create multiple parameter sets:

  1. Use the function rsimgetrtp to get a structure containing parameter information for the example model rtwdemo_rsimtf. Store the structure in a variable param_struct.

    param_struct = rsimgetrtp('rtwdemo_rsimtf');
    

  2. Use the function rsimsetrtpparam to expand the structure so that it contains more parameter sets. In this case, create two more parameter sets (for a total of three sets).

    param_struct = rsimsetrtpparam(param_struct,3);

    The function converts the parameters field to a cell array with three elements. Each element contains information for a single parameter set. By default, the function creates the second and third elements of the cell array by copying the first element. Therefore, all of the parameter sets use the same parameter values.

  3. Change the values of block parameters or workspace variables. For example, change the value of the variable w from 70 to 72.

    w = 72;

  4. Use rimsgetrtp to get another structure containing parameter information. Store the structure in a temporary variable rtp_temp.

    rtp_temp = rsimgetrtp('rtwdemo_rsimtf');

  5. Assign the value of the parameters field of rtp_temp to the structure param_struct as a second parameter set.

    param_struct.parameters{2} = rtp_temp.parameters;

  6. Change the value of the variable w from 72 to 75.

    w = 75;

  7. Use rimsgetrtp to get another structure containing parameter information. Then, assign the value of the parameters field to param_struct as a third parameter set.

    rtp_temp = rsimgetrtp('rtwdemo_rsimtf');
    param_struct.parameters{3} = rtp_temp.parameters;

  8. Save the structure containing the parameter set information to a MAT-file.

    save rtwdemo_rsimtf.mat param_struct;

For more information on how to specify each parameter set when you run the simulations, see Change Block Parameters for an RSim Simulation.

Create a MAT-File for a From File Block

You can use a MAT-file as the input data source for a From File block. The format of the data in the MAT-file must match the data format expected by that block. For example, if you are using a matrix as an input for the MAT file, this cannot be different from the matrix size for the executable.

To create a MAT-file for a From File block:

  1. For array format data, in the workspace create a matrix that consists of two or more rows. The first row must contain monotonically increasing time points. Other rows contain data points that correspond to the time point in that column. The time and data points must be data of type double.

    For example:

    t=[0:0.1:2*pi]';
    Ina1=[2*sin(t) 2*cos(t)];
    Ina2=sin(2*t);
    Ina3=[0.5*sin(3*t) 0.5*cos(3*t)];
    var_matrix=[t Ina1 Ina2 Ina3]';

    For other supported data types, such as int16 or fixed-point, the time data points must be of type double, just as for array format data. However, the sample data can be of any dimension.

    For more information on setting up the input data, see the block description of From File.

  2. Save the matrix to a MAT-file.

    The following example saves the matrix var_matrix to the MAT-file myrsimdemo.mat in Version 7.3 format.

    save '-v7.3' myrsimdemo.mat var_matrix;

    Using a command-line option, you can then specify that MAT-file as input for rapid simulations.

Create a MAT-File for an Inport Block

You can use a MAT-file as the input data source for an Inport block.

The format of the data in the MAT-file must adhere to one of the three column-based formats listed in the following table. The table lists the formats in order from least flexible to most flexible.

FormatDescription
Single time/data matrix
  • Least flexible.

  • One variable.

  • Two or more columns. Number of columns must equal the sum of the dimensions of all root Inport blocks plus 1. First column must contain monotonically increasing time points. Other columns contain data points that correspond to the time point in a given row.

  • Data of type double.

For an example, see Single time/data matrix in the following procedure, step 4. For more information, see Loading Data Arrays to Root-Level Inputs.

Signal-and-time structure
  • More flexible than the single time/data matrix format.

  • One variable.

  • Must contain two top-level fields: time and signals. The time field contains a column vector of the simulation times. The signals field contains an array of substructures, each of which corresponds to an Inport block. The substructure index corresponds to the Inport block number. Each signals substructure must contain a field named values. The values field must contain an array of inputs for the corresponding Inport block, where each input corresponds to a time point specified by the time field.

  • If the time field is set to an empty value, clear the check box for the Inport block Interpolate data parameter.

  • Data type must match Inport block settings.

For an example, see Signal-and-time structure in the following procedure, step 4. For more information on this format, see Loading Data Structures to Root-Level Inputs.

Per-port structure
  • Most flexible

  • Multiple variables. Number of variables must equal the number of Inport blocks.

  • Consists of a separate structure-with-time or structure-without-time for each Inport block. Each Inport block data structure has only one signals field. To use this format, in the Input text field, enter the names of the structures as a comma-separated list, in1, in2,..., inN, where in1 is the data for your model's first port, in2 for the second port, and so on.

  • Each variable can have a different time vector.

  • If the time field is set to an empty value, clear the check box for the Inport block Interpolate data parameter.

  • Data type must match Inport block settings.

  • To save multiple variables to the same data file, you must save them in the order expected by the model, using the -append option.

For an example, see Per-port structure in the following procedure, step 4. For more information, see Loading Data Structures to Root-Level Inputs.

The supported formats and the following procedure are illustrated in rtwdemo_rsim_i.

To create a MAT-file for an Inport block:

  1. Choose one of the preceding data file formats.

  2. Update Inport block parameter settings and specifications to match specifications of the data to be supplied by the MAT-file.

    By default, the Inport block inherits parameter settings from downstream blocks. To import data from an external MAT-file, explicitly set the following parameters to match the source data in the MAT-file.

    • Main > Interpolate data

    • Signal Attributes > Port dimensions

    • Signal Attributes > Data type

    • Signal Attributes > Signal type

    If you choose to use a structure format for workspace variables and the time field is empty,clear block parameter Interpolate data or modify the parameter so that it is set to a nonempty value. Interpolation requires time data.

    For descriptions of the preceding block parameters, see the block description of Inport.

  3. Build an RSim executable program for the model. The build process creates and calculates a structural checksum for the model and embeds it in the generated executable. The RSim target uses the checksum to verify that data being passed into the model is consistent with what the model executable expects.

  4. Create the MAT-file that provides the source data for the rapid simulations. You can create the MAT-file from a workspace variable. Using the specifications in the preceding format comparison table, create the workspace variables for your simulations.

    An example of each format follows:

    Single time/data matrix

    t=[0:0.1:2*pi]';
    Ina1=[2*sin(t) 2*cos(t)];
    Ina2=sin(2*t);
    Ina3=[0.5*sin(3*t) 0.5*cos(3*t)];
    var_matrix=[t Ina1 Ina2 Ina3];

    Signal-and-time structure

    t=[0:0.1:2*pi]';
    var_single_struct.time=t;
    var_single_struct.signals(1).values(:,1)=2*sin(t);
    var_single_struct.signals(1).values(:,2)=2*cos(t);
    var_single_struct.signals(2).values=sin(2*t);
    var_single_struct.signals(3).values(:,1)=0.5*sin(3*t);
    var_single_struct.signals(3).values(:,2)=0.5*cos(3*t);
    v=[var_single_struct.signals(1).values...
    var_single_struct.signals(2).values...
    var_single_struct.signals(3).values];

    Per-port structure

    t=[0:0.1:2*pi]';
    Inb1.time=t;
    Inb1.signals.values(:,1)=2*sin(t);
    Inb1.signals.values(:,2)=2*cos(t);
    t=[0:0.2:2*pi]';
    Inb2.time=t;
    Inb2.signals.values(:,1)=sin(2*t);
    t=[0:0.1:2*pi]';
    Inb3.time=t;
    Inb3.signals.values(:,1)=0.5*sin(3*t);
    Inb3.signals.values(:,2)=0.5*cos(3*t);
  5. Save the workspace variables to a MAT-file.

    Single time/data matrix

    The following example saves the workspace variable var_matrix to the MAT-file rsim_i_matrix.mat.

    save rsim_i_matrix.mat var_matrix;

    Signal-and-time structure

    The following example saves the workspace structure variable var_single_struct to the MAT-file rsim_i_single_struct.mat.

    save rsim_i_single_struct.mat var_single_struct;

    Per-port structure

    To order data when saving per-port structure variables to a single MAT-file, use the save command's -append option. Be sure to append the data in the order that the model expects it.

    The following example saves the workspace variables Inb1, Inb2, and Inb3 to MAT-file rsim_i_multi_struct.mat.

    save rsim_i_multi_struct.mat Inb1;
    save rsim_i_multi_struct.mat Inb2 -append;
    save rsim_i_multi_struct.mat Inb3 -append;

    The save command does not preserve the order in which you specify your workspace variables in the command line when saving data to a MAT-file. For example, if you specify the variables v1, v2, and v3, in that order, the order of the variables in the MAT-file could be v2 v1 v3.

    Using a command-line option, you can then specify the MAT-files as input for rapid simulations.

Scripts for Batch and Monte Carlo Simulations

The RSim target is for batch simulations in which parameters and input signals vary for multiple simulations. New output file names allow you to run new simulations without overwriting prior simulation results. You can set up a series of simulations to run by creating a .bat file for use on a Microsoft® Windows® platform.

Create a file for the Windows platform with a text editor and execute it by typing the file name, for example, mybatch, where the name of the text file is mybatch.bat.

rtwdemo_rsimtf -f rtwdemo_rsimtf.mat=run1.mat -o results1.mat -tf 10.0
rtwdemo_rsimtf -f rtwdemo_rsimtf.mat=run2.mat -o results2.mat -tf 10.0
rtwdemo_rsimtf -f rtwdemo_rsimtf.mat=run3.mat -o results3.mat -tf 10.0
rtwdemo_rsimtf -f rtwdemo_rsimtf.mat=run4.mat -o results4.mat -tf 10.0

In this case, batch simulations run using four sets of input data in files run1.mat, run2.mat, and so on. The RSim executable saves the data to the files specified with the -o option.

The variable names containing simulation results in each of the files are identical. Therefore, loading consecutive sets of data without renaming the data once it is in the MATLAB workspace results in overwriting the prior workspace variable with new data. To avoid overwriting, you can copy the result to a new MATLAB variable before loading the next set of data.

You can also write MATLAB scripts to create new signals and new parameter structures, as well as to save data and perform batch runs using the bang command (!).

For details on running simulations and available command-line options, see Run Rapid Simulations. For an example of a rapid simulation batch script, see the example Run Batch Simulations Without Recompiling Generated Code.

Run Rapid Simulations

Rapid Simulations

Using the RSim target, you can build a model once and run multiple simulations to study effects of varying parameter settings and input signals. You can run a simulation directly from your operating system command line, redirect the command from the MATLAB command line by using the bang (!) character, or execute commands from a script.

From the operating system command line, use

rtwdemo_rsimtf

From the MATLAB command line, use

!rtwdemo_rsimtf

The following table lists ways you can use RSim target command-line options to control a simulation.

To...Use...
Read input data for a From File block from a MAT-file other than the MAT-file used for the previous simulation

model -f oldfilename.mat=newfilename.mat

Print a summary of the options for RSim executable targetsexecutable filename -h
Read input data for an Inport block from a MAT-file model -i filename.mat
Time out after n clock time seconds, where n is a positive integer value model -L n
Write MAT-file logging data to file filename.mat model -o filename.mat
Read a parameter vector from file filename.mat model -p filename.mat
Override the default TCP port (17725) for external mode model -port TCPport
Write MAT-file logging data to a MAT-file other than the MAT-file used for the previous simulation model -t oldfilename.mat=newfilename.mat
Run the simulation until the time value stoptime is reached model -tf stoptime
Run in verbose mode model -v
Wait for the Simulink engine to start the model in external mode model -w

The following sections use the rtwdemo_rsimtf example model in examples to illustrate some of these command-line options. In each case, the example assumes you have already done the following:

  • Created or changed to a working folder.

  • Opened the example model.

  • Copied the data file matlabroot/toolbox/rtw/rtwdemos/rsimdemos/rsim_tfdata.mat to your working folder. You can perform this operation using the command:

    copyfile(fullfile(matlabroot,'toolbox','rtw','rtwdemos',...
    'rsimdemos','rsim_tfdata.mat'),pwd);

Requirements for Running Rapid Simulations

The following requirements apply to both fixed and variable step executables.

  • You must run the RSim executable on a computer configured to run MATLAB. Also, the RSim.exe file must be able to access the MATLAB and Simulink installation folders on this machine. To obtain that access, your PATH environment variable must include /bin and /bin/($ARCH), where ($ARCH) represents your operating system architecture. For example, for a personal computer running on a Windows platform, ($ARCH) is “win64”, whereas for a Linux machine, ($ARCH) is “glnxa64”.

  • On GNU® Linux® platforms, to run an RSim executable, define the LD_LIBRARY_PATH environment variable to provide the path to the MATLAB installation folder, as follows:

    % setenv LD_LIBRARY_PATH /matlab/sys/os/glnx64:$LD_LIBRARY_PATH

  • On the Apple Macintosh OS X platform, to run RSim target executables, you must define the environment variable DYLD_LIBRARY_PATH to include the folders bin/mac and sys/os/mac under the MATLAB installation folder. For example, if your MATLAB installation is under /MATLAB, add /MATLAB/bin/mac and /MATLAB/sys/os/mac to the definition for DYLD_LIBRARY_PATH.

Set a Clock Time Limit for a Rapid Simulation

If a model experiences frequent zero crossings and the model's minor step size is small, consider setting a time limit for a rapid simulation. To set a time limit, specify the -L option with a positive integer value. The simulation aborts after running for the specified amount of clock time (not simulation time). For example,

  !rtwdemo_rsimtf -L 20

Based on your clock, after the executable runs for 20 seconds, the program terminates. You see a message similar to one of the following:

  • On a Microsoft Windows platform,

    Exiting program, time limit exceeded
    Logging available data ...
  • On The Open Group UNIX® platform,

    ** Received SIGALRM (Alarm) signal @ Fri Jul 25 15:43:23 2003
    ** Exiting model  'vdp' @ Fri Jul 25 15:43:23 2003

You do not need to do anything to your model or to its configuration to use this option.

Override a Model Simulation Stop Time

By default, a rapid simulation runs until the simulation time reaches the time specified the Configuration Parameters dialog box, on the Solver pane. You can override the model simulation stop time by using the -tf option. For example, the following simulation runs until the time reaches 6.0 seconds.

!rtwdemo_rsimtf -tf 6.0

The RSim target stops and logs output data using MAT-file data logging rules.

If the model includes a From File block, the end of the simulation is regulated by the stop time setting specified in the Configuration Parameters dialog box, on the Solver pane, or with the RSim target option -tf. The values in the block's time vector are ignored. However, if the simulation time exceeds the endpoints of the time and signal matrix (if the final time is greater than the final time value of the data matrix), the signal data is extrapolated to the final time value.

Read the Parameter Vector into a Rapid Simulation

To read the model parameter vector into a rapid simulation, you must first create a MAT-file that includes the parameter structure as described in Create a MAT-File That Includes a Model Parameter Structure. You can then specify the MAT-file in the command line with the -p option.

For example:

  1. Build an RSim executable for the example model rtwdemo_rsimtf.

  2. Modify parameters in your model and save the parameter structure.

    param_struct = rsimgetrtp('rtwdemo_rsimtf');
    save myrsimdata.mat param_struct
  3. Run the executable with the new parameter set.

    !rtwdemo_rsimtf -p myrsimdata.mat
    
    ** Starting model 'rtwdemo_rsimtf' @ Tue Dec 27 12:30:16 2005 
    ** created rtwdemo_rsimtf.mat **
  4. Load workspace variables and plot the simulation results by entering the following commands:

    load myrsimdata.mat
    plot(rt_yout)

Specify New Signal Data File for a From File Block

If your model's input data source is a From File block, you can feed the block with input data during simulation from a single MAT-file or you can change the MAT-file from one simulation to the next. Each MAT-file must adhere to the format described in Create a MAT-File for a From File Block.

To change the MAT-file after an initial simulation, you specify the executable with the -f option and an oldfile.mat=newfile.mat parameter, as shown in the following example.

  1. Set some parameters in the MATLAB workspace. For example:

    w = 100;
    theta = 0.5;
  2. Build an RSim executable for the example model rtwdemo_rsimtf.

  3. Run the executable.

    !rtwdemo_rsimtf

    The RSim executable runs a set of simulations and creates output MAT-files containing the specific simulation result.

  4. Load the workspace variables and plot the simulation results by entering the following commands:

    load rtwdemo_rsimtf.mat
    plot(rt_yout)

    The resulting plot shows simulation results based on default input data.

  5. Create a new data file, newfrom.mat, that includes the following data:

    t=[0:.001:1];
    u=sin(100*t.*t);
    tu=[t;u];
    save newfrom.mat tu;
  6. Run a rapid simulation with the new data by using the -f option to replace the original file, rsim_tfdata.mat, with newfrom.mat.

    !rtwdemo_rsimtf -f rsim_tfdata.mat=newfrom.mat
  7. Load the data and plot the new results by entering the following commands:

    load rtwdemo_rsimtf.mat
    plot(rt_yout)

    The next figure shows the resulting plot.

From File blocks require input data of type double. If you need to import signal data of a data type other than double, use an Inport block (see Create a MAT-File for an Inport Block) or a From Workspace block with the data specified as a structure.

Workspace data must be in the format:

variable.time
variable.signals.values

If you have more than one signal, use the following format:

variable.time
variable.signals(1).values
variable.signals(2).values

Specify Signal Data File for an Inport Block

If your model's input data source is an Inport block, you can feed the block with input data during simulation from a single MAT-file or you can change the MAT-file from one simulation to the next. Each MAT-file must adhere to one of the three formats described in Create a MAT-File for an Inport Block.

To specify the MAT-file after a simulation, you specify the executable with the -i option and the name of the MAT-file that contains the input data. For example:

  1. Open the model rtwdemo_rsim_i.

  2. Check the Inport block parameter settings. The following Inport block data parameter settings and specifications that you specify for the workspace variables must match settings in the MAT-file, as indicated in Configure Inports to Provide Simulation Source Data:

    • Main > Interpolate data

    • Signal Attributes > Port dimensions

    • Signal Attributes > Data type

    • Signal Attributes > Signal type

  3. Build the model.

  4. Set up the input signals. For example:

    t=[0:0.01:2*pi]';
    s1=[2*sin(t) 2*cos(t)];
    s2=sin(2*t);
    s3=[0.5*sin(3*t) 0.5*cos(3*t)];
    plot(t, [s1 s2 s3])

  5. Prepare the MAT-file by using one of the three available file formats described in Create a MAT-File for an Inport Block. The following example defines a signal-and-time structure in the workspace and names it var_single_struct.

    t=[0:0.1:2*pi]';
    var_single_struct.time=t;
    var_single_struct.signals(1).values(:,1)=2*sin(t);
    var_single_struct.signals(1).values(:,2)=2*cos(t);
    var_single_struct.signals(2).values=sin(2*t);
    var_single_struct.signals(3).values(:,1)=0.5*sin(3*t);
    var_single_struct.signals(3).values(:,2)=0.5*cos(3*t);
    v=[var_single_struct.signals(1).values...
    var_single_struct.signals(2).values...
    var_single_struct.signals(3).values];
  6. Save the workspace variable var_single_struct to MAT-file rsim_i_single_struct.

    save rsim_i_single_struct.mat var_single_struct;
  7. Run a rapid simulation with the input data by using the -i option. Load and plot the results.

    !rtwdemo_rsim_i -i rsim_i_single_struct.mat
    
    ** Starting model 'rtwdemo_rsim_i' @ Tue Aug 19 10:26:53 2014 
     *** rsim_i_single_struct.mat is successfully loaded! *** 
    ** created rtwdemo_rsim_i.mat ** 
     
    ** Execution time = 0.02024185130718954s
  8. Load and plot the results.

    load rtwdemo_rsim_i.mat
    plot(rt_tout, rt_yout);

Change Block Parameters for an RSim Simulation

As described in Create a MAT-File That Includes a Model Parameter Structure, after you alter one or more parameters in a Simulink block diagram, you can extract the parameter vector, model_P, for the entire model. You can then save the parameter vector, along with a model checksum, to a MAT-file. This MAT-file can be read directly by the standalone RSim executable, allowing you to replace the entire parameter vector or individual parameter values, for running studies of variations of parameter values representing coefficients, new data for input signals, and so on.

RSim can read the MAT-file and replace the entire model_P structure whenever you change one or more parameters, without recompiling the entire model.

For example, assume that you changed one or more parameters in your model, generated the new model_P vector, and saved model_P to a new MAT-file called mymatfile.mat. To run the same rtwdemo_rsimtf model and use these new parameter values, use the -p option, as shown in the following example:

!rtwdemo_rsimtf -p mymatfile.mat
load rtwdemo_rsimtf 
plot(rt_yout)

If you have converted the parameter structure to a cell array for running simulations on varying data sets, as described in Convert the Parameter Structure for Running Simulations on Varying Data Sets, you must add an @n suffix to the MAT-file specification. n is the element of the cell array that contains the specific input that you want to use for the simulation.

The following example converts param_struct to a cell array, changes parameter values, saves the changes to MAT-file mymatfile.mat, and then runs the executable using the parameter values in the second element of the cell array as input.

param_struct = rsimgetrtp('rtwdemo_rsimtf');
param_struct = rsimsetrtpparam(param_struct,2);
param_struct.parameters{1}
ans = 

       dataTypeName: 'double'
         dataTypeId: 0
            complex: 0
         dtTransIdx: 0
             values: [-140 -4900 0 4900]
                map: []
    structParamInfo: []
param_struct.parameters{2}.values=[-150 -5000 0 4950];
save mymatfile.mat param_struct;
!rtwdemo_rsimtf -p mymatfile.mat@2 -o rsim2.mat

Specify a New Output File Name for a Simulation

If you have specified one or more of the Save to Workspace parameters — Time, States, Outputs, or Final States — in the Configuration Parameters dialog box, on the Data Import/Export pane, the default is to save simulation logging results to the file model.mat. For example, the example model rtwdemo_rsimtf normally saves data to rtwdemo_rsimtf.mat, as follows:

!rtwdemo_rsimtf
created rtwdemo_rsimtf.mat

You can specify a new output file name for data logging by using the -o option when you run an executable.

!rtwdemo_rsimtf -o rsim1.mat

In this case, the set of parameters provided at the time of code generation, including From File block data parameters, is run.

Specify New Output File Names for To File Blocks

In much the same way as you can specify a new system output file name, you can also provide new output file names for data saved from one or more To File blocks. To do this, specify the original file name at the time of code generation with a new name, as shown in the following example:

!rtwdemo_rsimtf -t rtwdemo_rsimtf_data.mat=mynewrsimdata.mat

In this case, assume that the original model wrote data to the output file rtwdemo_rsimtf_data.mat. Specifying a new file name forces RSim to write to the file mynewrsimdata.mat. With this technique, you can avoid overwriting an existing simulation run.

Tune Parameters Interactively During Rapid Simulation

The RSim system target file was designed to let you run batch simulations at the fastest possible speed. Using variable-step or fixed-step solvers with that system target file and a tunable parameter data structure, whether you set Default parameter behavior to Tunable or to Inlined, you can create multiple parameter sets. You can run the data sets with the generated executable program (.exe on Windows). Each invocation of the executable program allows specification of the file name to use for results.

For this example, Default parameter behavior is set to Inlined. The model declares workspace variables as tunable parameters. To use the RSim system target file with Default parameter behavior set to Tunable, and without explicitly declaring tunable parameters, see Run Batch Simulations Without Recompiling Generated Code.

Open Example Model

Open the example model rtwdemo_rsim_param_tuning.

open_system('rtwdemo_rsim_param_tuning');

This model uses the RSim target and the rsimgetrtp function to allow a non real time executable to be passed new data without the need to recompile the Simulink model. This feature allows you to get a map of the tunable parameters declared in a model and save it in a MAT-file. You can then create your own MATLAB GUI or a standalone GUI (independent of MATLAB) to read and write the MAT-file and rerun the executable to produce new output files.

In the model, double-click the buttons sequentially to run the example.

To review the code used to create the MATLAB graphical interface and the standalone graphical interface, double-click the View MATLAB programs button.

For more information, see Accelerate, Refine, and Test Hybrid Dynamic System on Host Computer by Using RSim System Target File.

Rapid Simulation Target Limitations

The RSim target has the following limitations:

  • Does not support algebraic loops.

  • Does not support Interpreted MATLAB Function blocks.

  • Does not support noninlined MATLAB language or Fortran S-functions.

  • If an RSim build includes referenced models (by using Model blocks), set up these models to use fixed-step solvers to generate code for them. The top model, however, can use a variable-step solver as long as the blocks in the referenced models are discrete.

  • In certain cases, changing block parameters can result in structural changes to your model that change the model checksum. An example of such a change is changing the number of delays in a DSP simulation. In such cases, you must regenerate the code for the model.

Related Topics