Main Content

loadVariablesFromExternalSource

Load variables from a custom file into Simulink.SimulationInput object

Since R2022b

Description

simIn = loadVariablesFromExternalSource(simIn,'filename') loads variables from the custom file filename into the Variables property of the Simulink.SimulationInput object simIn using the custom adapter registered for the file format.

simIn = loadVariablesFromExternalSource(simIn,'filename',Name,Value) loads variables from a custom file into the Variables property of a Simulink.SimulationInput object simIn with options specified using one or more name-value arguments.

For information on writing a custom file adapter, see Create External File Adapter for Loading Variables into Simulink.SimulationInput Object.

example

Examples

collapse all

This example shows how you can load variables into a Simulink.SimulationInput object from a custom file source, and run parallel simulations with those variables. To enable this, write and register an adapter. In this example, we use a model of a road suspension system. that we want to simulate with different sets of variables. The set of variables and their values for simulations is stored in the Excel files CompactAndMidsizeCar.xls and LargeCars.xls

For the simulations, we have stored different sets of variable values in the Excel files CompactAndMidsizeCar.xls and LargeCars.xls. Normally, you write a script to load variables into the base workspace, and then run your simulation. In this example, you load the variables directly into a Simulink.SimulationInput object and run simulations without changing the base workspace.

Register Adapter

To load the variables from a custom file format, you first must to write and register an adapter. Simulink.data.adapters.excel_example_adapter enables loading data from your custom file format. For more information on creating and registering adapters, see..

Simulink.data.adapters.registerAdapter('Simulink.data.adapters.excel_example_adapter')
ans = logical
   1

Create Simulink.SimulationInput Object

First, create the Simulink.SimulationInput object for the ex_loadvar_sldemo_suspn_3dof model.

mdl = 'ex_loadvar_sldemo_suspn_3dof';
in = Simulink.SimulationInput(mdl)
in = 
  SimulationInput with properties:

               ModelName: 'ex_loadvar_sldemo_suspn_3dof'
            InitialState: [0x0 Simulink.op.ModelOperatingPoint]
           ExternalInput: []
         ModelParameters: [0x0 Simulink.Simulation.ModelParameter]
         BlockParameters: [0x0 Simulink.Simulation.BlockParameter]
               Variables: [0x0 Simulink.Simulation.Variable]
               PreSimFcn: []
              PostSimFcn: []
              UserString: ''
    VariantConfiguration: ''

Load Variables from External File Source

You can now use the adapter to load variables from Excel files into a SimulationInput object by using the loadVariablesFromExternalSource function.

Multiple variable sets are saved in different files and in different sheets. To load the variables, first create a cell array named fileAndSectionNames of file-section paris. Each row in this cell array represents the data for a single simulation. Section represents the sheet or sheets present in the excel files.

fileAndSectionNames = { 
                        {'CompactAndMidsizeCar.xls', 'CompactCar'};
                        {'CompactAndMidsizeCar.xls', 'Midsize'};
                        {'LargeCars.xls', 'LargeCar'};
                        {'LargeCars.xls', 'LargeSUV'};
                        }
fileAndSectionNames=4×1 cell array
    {1x2 cell}
    {1x2 cell}
    {1x2 cell}
    {1x2 cell}

Next, create an array of Simulink.SimulationInput objects and use the loadVariablesFromExternalSource method to load the variable sets into the array. To load variables from specific sheets from the excel files, use the 'Section' argument of the loadVariablesFromExternalSource method.

simIn = Simulink.SimulationInput.empty(length(fileAndSectionNames), 0);
for i = 1 : length(fileAndSectionNames)
    simIn(i) = Simulink.SimulationInput(mdl);    
    simIn(i) = simIn(i).loadVariablesFromExternalSource(fileAndSectionNames{i}{1}, ...
                                                'Section', fileAndSectionNames{i}{2})
end
simIn = 
  SimulationInput with properties:

               ModelName: 'ex_loadvar_sldemo_suspn_3dof'
            InitialState: [0x0 Simulink.op.ModelOperatingPoint]
           ExternalInput: []
         ModelParameters: [0x0 Simulink.Simulation.ModelParameter]
         BlockParameters: [0x0 Simulink.Simulation.BlockParameter]
               Variables: [1x5 Simulink.Simulation.Variable]
               PreSimFcn: []
              PostSimFcn: []
              UserString: ''
    VariantConfiguration: ''

simIn=1×2 SimulationInput array with properties:
    ModelName
    InitialState
    ExternalInput
    ModelParameters
    BlockParameters
    Variables
    PreSimFcn
    PostSimFcn
    UserString
    VariantConfiguration

simIn=1×3 SimulationInput array with properties:
    ModelName
    InitialState
    ExternalInput
    ModelParameters
    BlockParameters
    Variables
    PreSimFcn
    PostSimFcn
    UserString
    VariantConfiguration

simIn=1×4 SimulationInput array with properties:
    ModelName
    InitialState
    ExternalInput
    ModelParameters
    BlockParameters
    Variables
    PreSimFcn
    PostSimFcn
    UserString
    VariantConfiguration

Run Multiple Simulations

To run multiple simulations, use the parsim function with the Simulink.SimulationInput object. Data in each file is isolated and has no impact on simulations that use data from the other files, regardless of the order in which the files are specified.

simOut = parsim(simIn)
[05-Sep-2024 19:21:02] Checking for availability of parallel pool...
Starting parallel pool (parpool) using the 'Processes' profile ...
Connected to parallel pool with 4 workers.
[05-Sep-2024 19:21:57] Starting Simulink on parallel workers...
[05-Sep-2024 19:22:47] Configuring simulation cache folder on parallel workers...
[05-Sep-2024 19:22:47] Loading model on parallel workers...
[05-Sep-2024 19:23:24] Running simulations...
[05-Sep-2024 19:23:37] Completed 1 of 4 simulation runs
[05-Sep-2024 19:23:37] Received simulation output (size: 3.06 MB) for run 1 from parallel worker.
[05-Sep-2024 19:23:37] Completed 2 of 4 simulation runs
[05-Sep-2024 19:23:37] Received simulation output (size: 3.06 MB) for run 2 from parallel worker.
[05-Sep-2024 19:23:37] Completed 3 of 4 simulation runs
[05-Sep-2024 19:23:37] Received simulation output (size: 3.06 MB) for run 3 from parallel worker.
[05-Sep-2024 19:23:38] Completed 4 of 4 simulation runs
[05-Sep-2024 19:23:38] Received simulation output (size: 3.06 MB) for run 4 from parallel worker.
[05-Sep-2024 19:23:38] Cleaning up parallel workers...
simOut = 
1x4 Simulink.SimulationOutput array


To plot the results, plotResult uses a MATLAB® timeseries object. The timeseries object ts stores the time and data values for the logged signal. The plot function plots the data against the simulation time. The plot shows the results for the simulations that uses the variable values loaded from the Excel files.

plotResult(fileAndSectionNames, simOut)

Figure contains an axes object. The axes object with title Response of a 3-DoF Suspension Model, xlabel Time (s), ylabel Vehicle vertical displacement (m) contains 4 objects of type line. These objects represent CompactCar, Midsize, LargeCar, LargeSUV.

As the last step, unregister the adapter.

Simulink.data.adapters.unregisterAdapter('Simulink.data.adapters.excel_example_adapter')
ans = logical
   1

Input Arguments

collapse all

Simulation inputs and configuration, specified as a Simulink.SimulationInput object.

Name of custom external file, specified as a character vector or a string.

To use a custom file format, register an adapter that the method loadVariablesFromExternalSource uses to load variables from filename into the Simulink.SimulationInput object. filename must be specified with its extension.

Example: 'myFile'

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: simIn = loadVariablesFromExternalSource(simIn,'filename','Append','on')

Section names in custom file from which variables are loaded, specified as a character vector or a string.

Option to append new loaded variables to existing variables in a Simulink.SimulationInput object, specified as 'off' or 'on'.

By default, the loaded variables and their values override the variables and values already present in the Variable property of the Simulink.SimulationInput object.

Workspace for loaded variables, specified as 'global-workspace' or 'modelName'.

Context for loaded variables within global workspace, specified as a string.

When the parameter 'EnforceDataConsistency' is set to off, the current model and the models below it in the model hierarchy can use variables with the same name but different values as long as each model in the hierarchy can see only one definition of the variable. These variables that have the same name are only attached to their respective models. In such a case, the Context option allows you to set the scope of the variable.

Output Arguments

collapse all

Simulation configuration with variables from custom file format added, returned as a Simulink.SimulationInput object.

Version History

Introduced in R2022b