Simulink - Interfacing with MATLAB (2022)

Interfacing Simulink with MATLAB

Simulink, being an add-on product to MATLAB, is very tightly integrated with MATLAB.

Although rarely done, it is possible tobuild a Simulink model from MATLAB codewithout ever using the Simulink user interface.This is achieved using the MATLAB-Simulink API (application program interface) commands.

More commonly, MATLAB is the environment used to pre- and post-process model parametersand signal data used in or generated by Simulink.This tutorial discusses some of the different ways that MATLAB and Simulink interact.The topics covered are,

  1. Specifying Model Parameters.
  2. Workspaces.
  3. Inputting Signal Data.
  4. Outputting Signal Data.
  5. Simulating from the MATLAB Command Line.

The model used throughout this tutorial is called simpleModel. It is constucted in the tutorial Simulink Essentials - Building, Simulating and Visualizing Models.

Other tutorials discussing Simulink and its applications for model based design are available on the Software Tutorials page.

Specifying Model Parameters

The gain in the transfer function modeled by the simpleModel developed in the tutorial Simulink Essentials - Building, Simulating and Visualizing Models has been hard-coded to have a value of 2. However the model can be used to model a generic first order transfer function, i.e. it can be used to simulate the step response of a transfer function with an arbitrary gain.

Rather than give the gain a specific (hard-coded, numeric) value, it is much better to parameterize it, i.e. to put the name of a MATLAB variable as the gain value. This is shown in Figure 1. More generally all model and block parameters should be defined as variables.

Simulink - Interfacing with MATLAB (1)

Figure 1: Parameterizing a Model.

One of the first things Simulink does when the simulation is started is inspect the model and determinewhat parameters it needs for the simulation to run correctly.One of the places it looks for parameter values is the MATLAB Workspace.In the above case the variable K has been defined in the MATLAB Workspace and Simulink will obtainthe value for K -- in this case 2 -- and use it for this simulation run.

If the step response of a transfer with a different gain is required then K can be redefined in the MATLABWorkspace and the simulation executed again.

(Video) Texas Instruments C2000 and MATLAB Simulink Interfacing

Parameterization isn't too critical for very simple models such as simpleModel.The gain only appears once in the model and its value would be easy to change in the model itself.However as models become larger and more complex, and the same parameter is used in multiple placesin a model, it becomes much more important to use a parameterized model.In this way the value of a gain (or any other model parameter) can be changed in one place (i.e. theMATLAB Workspace) and the new value will be used everywhere that the parameter is used in the model.

Workspaces

The term Workspace is MATLAB terminology for memory allocated to store data. Each MATLAB funcion has its own workspace, or memory allocated for it to create and destroy its locally scoped variables.

In Simulink each model has access to two workspaces: the MATLAB Base Workspace; and the Model Workspace. Each model has its own Model Workspace.

When a parameterized model is intialized it must be given values for the parameters that it needs. The model first looks in its Model Workspace to determine if any of the required parameters are present, and if they are then those values are used. If any variables are not defined in the model’s workspace then Simulink will look for them in the MATLAB Base Workspace. If the same variable exists in both locations then the value in the model’s workspace takes precedence.

The Model Workspace is created, viewed and modified via the Model Explorer. The Model Explorer is opened using the View→Model Explorer pull-down menu (see Figure 2).

Simulink - Interfacing with MATLAB (2)

Figure 2: Opening the Model Explorer.

Once the Model Explorer is open then the model’s workspace can be viewed by selecting the appropriate node of the tree view down the left hand side. Figure 3 shows a value for the gain K being defined in simpleModel’s model workspace.

Simulink - Interfacing with MATLAB (3)

Figure 3: Looking at the Model Workspace.

Note that there are several different ways to define the model workspace.Data may be defined either as m-code that defines the appropriate variables and gets automatically executed to create the variables, or within a .mat file that gets automatically loaded to createthe variables.

Inputting Signal Data

Very often a user may wish to excite a model with externally created data. This may be artificially created or true test data from field tests.

(Video) Model-Based Design with MATLAB and Simulink

If the data is stored in a .mat (binary MATLAB) data file then it may be imported into the model using a From File block.

If the data is in the MATLAB workspace then it may be imported using either a From Workspace block or an Inport Block. If an Inport block is used then the specific data to be used must be defined on the Data Import/Export pane of the Simulation→Configuration Parameters pull-down menu. (Initial values for the model states may also be specified on this panel.)

In all cases the data must be of a specific format. The data must be either a multicolumn matrix where the first column represents time (corresponding to the data in subsequent columns), or it must be a MATLAB structure data type with a field called time and another field with the signal data.

Figure 4 shows the simpleModel where the input Step block has been replaced by an Inport block. Figure 5 shows the Data Import/Export panel of the modified model’s Configuration Parameters dialog. To excite the model through the Inport block the Input check-box must be checked and appropriate data defined. In this case the input has been parameterized with the name of a MATLAB variable. Figure 6 shows one of the ways to define the required data in the MATLAB workspace. An appropriate structure is created that contains data defining a unit step function where the step takes place at t=1.

Simulink - Interfacing with MATLAB (4)

Figure 4: Model Excited Using an Inport Block.

Simulink - Interfacing with MATLAB (5)

Figure 5: Defining Inport Data.

Simulink - Interfacing with MATLAB (6)

Figure 6: Creating the Data in MATLAB.

Figure 7 shows the output Scope when the model is simulated using the datafed through the Inport block.As expected it shows the step response of a first order transfer function.

Simulink - Interfacing with MATLAB (7)

Figure 7: Output When Excited Through the Inport.

Outputting Signal Data

Signal and state data can easily be saved at the completion of a simulation. (For reasons of efficiency data is not saved back to MATLAB during the simulation – only when the simulation is paused or stops.)

(Video) Interfacing NI myDAQ with Matlab Simulink

If the data is to be stored in a .mat (binary MATLAB) data file then it may be exported using a To File block.

It is more typical for signal data to be exported to MATLAB for post-processing.This may be achieved in numerous ways.The To Workspace block is a straight forward approach.However using an Outport (at the highest level of the model) or saving the data/signal being fedinto a Scope block are more common approaches.

If an Outport block is used then the signal data is saved to the MATLAB Workspace.The name of the variable to create is define on theData Import/Export pane of the Simulation→Configuration Parameters pull-down menu.

Several different formats for the saved data are available including a matrix,a structure with time and a structure without time.There are also options for automatically decimating the data (i.e. only saving every n-th time step)and only saving data for the last n number of time steps.

Figure 8 shows the simpleModel where the display Scope block has been replaced by an Outport block. Figure 9 shows the Data Import/Export panel of the modified model’s Configuration Parameters dialog. To save signal data through the Outport block the appropriate Save To Workspace check-boxes must be checked and appropriate variable names specified. In this case the model will save both the simulation time steps (in the variable tout) and the signal being fed into the Outport (in the variable yout).

Simulink - Interfacing with MATLAB (8)

Figure 8: Exporting Data Using an Outport Block.

Simulink - Interfacing with MATLAB (9)

Figure 9: Defining Outport Data.

Once the simulation has been run the variables tout and yout will be saved to the MATLABWorkspace.Being standard MATLAB variables they may be post-process in any way the user wished to program.Figure 10 shows the appropriate MATLAB command to plot the data.As expected it shows the step response of a first order transfer function.

Simulink - Interfacing with MATLAB (10)

Figure 10: Plot of the Output Saved Through an Outport.

Simulating from the MATLAB Command Line

Once a model has been created and parameterized it can be simulated directly from the MATLAB command line, or more often from within a MATLAB function or script file. The function to do this is called sim.

(Video) Creating a Simulink Block Using MATLAB Code

The sim function has several different formats (shown in Figure 11) for allowing the user to override the model parameters set on the model’s Configuration Parameters dialog. In each of these cases the sim function returns a Simulink.SimulationOutput object that contains all of the data that the model would normally save to the MATLAB Workspace.

simOut = sim('model', 'ParameterName1',Value1,'ParameterName2', Value2...);simOut = sim('model', ParameterStruct);simOut = sim('model', ConfigSet);
Figure 11: Different Syntaxes for the sim Function.

The following code snippet will run the model called inputOutputModel ten times,each time with a different gain value.inputOutputModel is a modification of the simpleModel model (which is constucted in the tutorial Simulink Essentials - Building, Simulating and Visualizing Models) so that its output is saved to the MATLAB Workspace through an outport as discussed in the above Outputting Signal Data section and the gain is parameterized as discussed in the above Specifying Model Parameters section.

for K = 1:10 data(K) = sim('inputOutputModel','ReturnWorkspaceOutputs', 'on');end
Figure 12: Code to Execute inputOutputModel Ten Times.

Note that each time through the loop in Figure 12 the value of thegain in the gain block changes and hence the rise time of the first order transfer functionbeing simulated will change.

After the code in Figure 12 is executed the MATLAB Workspace will have the followingvariable defined in it,

>> data1x10 Simulink.SimulationOutput array:
Figure 13: Data Defined in the MATLAB Workspace.

Each of the 10 elements of the Simulink.SimulationOutput object represents one of the 10different simulation runs.Hence each element contains signal data showing a different rise time for the first ordertansfer function being modeled.

The following code (see Figure 14) will extract the signal data saved to theSimulink.SimulationOutput object and overlay all 10 simulations on the same plot.The resulting plot is shown in Figure 15

for idx = 1:length(data) plot(get(data(idx),'tout'),get(data(idx),'yout'),'LineWidth',4); hold allendgrid on
Figure 14: Code to Plot the Ten Step Responses.

Simulink - Interfacing with MATLAB (11)

Figure 15: Plot Data Saved Using the sim Function.

This tutorial has discussed topics related to interfacing a Simulink model to MATLAB. Other Simulink tutorials are available on the Software Tutorials page.

Back To Top | Simulink Tutorials

FAQs

WHAT IS interface in Simulink? ›

Create models with time-based and event-based components, choose solvers, save simulation state. A SimEvents® model can coexist with time-based systems in a Simulink® model. The combination of time- and event-based modeling facilitates the simulation of large-scale sophisticated hybrid systems.

Is Simulink included with MATLAB? ›

Simulink provides a graphical editor, customizable block libraries, and solvers for modeling and simulating dynamic systems. It is integrated with MATLAB®, enabling you to incorporate MATLAB algorithms into models and export simulation results to MATLAB for further analysis.

How link MATLAB code to Simulink? ›

Make sure your existing MATLAB function is on your MATLAB path. Then, add a MATLAB Function block to your model with the same inputs and outputs as your existing MATLAB function, and then simply call your function from inside the MATLAB Function block.

Is MATLAB and MATLAB Simulink different? ›

Whereas, MATLAB is for the mathematical based algorithm development and which will not consider the time while in simulation (independent of time). Simulink is graphical and more interactive to the user. Whereas the Matlab is coding based approach based on the different function available in Matlab.

Is Simulink free with MATLAB? ›

You'd have to buy it.

How do I start MATLAB and Simulink? ›

Learn the Basics
  1. See Getting Started Documentation. Explore our step-by-step examples and tutorials. Read documentation.
  2. Start with an Example. Explore thousands of code and model examples for a head start solving your problem. Browse examples.
  3. Get a Detailed Look at Simulink. Interested in learning more?

What is Simulink in MATLAB with example? ›

Simulink examples include scripts and model files that guide you through modeling and simulating various dynamic systems. Using a Simulink Project to manage the files within your design. Regulating the speed of an electric motor. Modeling a bouncing ball using Simulink.

Is Simulink easier than MATLAB? ›

Simulink has Graphical User Interface (GUI) whereas Matlab is just code. Simulink's GUI lends it more intuitiveness. Simulink supports hardware communication. You can write a PID controller in Simulink and download it to Arduino.

Which is the good alternative to Simulink? ›

Top 10 Alternatives to Simulink
  • GNU Octave.
  • NI Multisim.
  • Scilab.
  • COMSOL Multiphysics (formerly FEMLAB)
  • Fusion 360.
  • Ansys Fluent.
  • SOLIDWORKS.
  • Inventor.

Is Simulink a programming language? ›

Simulink, also developed by MathWorks, is a data flow graphical programming language tool for modelling, simulating and analyzing multi-domain dynamic systems.

How do I transfer data from MATLAB to Simulink? ›

How to Bring Data from MATLAB Into Simulink - YouTube

How do I transfer data to Simulink? ›

To import many signals to root-level input ports, consider using the Root Inport Mapper tool. From File block — Read data from a MAT-file, outputting the data as a signal.
...
Signal Data Loading.
InportCreate input port for subsystem or external input
From FileLoad data from MAT file into Simulink model
7 more rows

How can I open Simulink in MATLAB online? ›

Just sign into MATLAB Online with your MathWorks account and either start Simulink or open a Simulink model.

What is Simulink Modelling? ›

A model is an abstract and simplified description of a system using mathematical equations and diagrams. The modeling concepts in this topic provide context for understanding the process of mathematically describing a system with Simulink® software tools.

Is MATLAB used in industry? ›

In industry, MATLAB is the tool of choice for high-productivity research, development, and analysis. MATLAB features a family of application-specific solutions called toolboxes. Very important to most users of MATLAB, toolboxes allow you to learn and apply specialized technology.

What is Matlab interface? ›

Graphical user interfaces (GUIs), also known as apps, provide point-and-click control of your software applications, eliminating the need for others to learn a language or type commands in order to run the application. You can share apps both for use within MATLAB and also as standalone desktop or web apps.

What is interfacing in Matlab? ›

The interface is an abstract class that defines properties and methods that the subclasses must implement, but does not specify how to implement these components.

Videos

1. How to Display Simulink Results on GUI in Matlab
(Chhira Tech)
2. MPU6050, Arduino Mega2560 & MATLAB Simulink Interfacing
(School of Engineering)
3. Configure and run pendulum Simulink model using App Designer in Matlab | 1
(Hussein Hamadi)
4. Acquiring Data from Sensors and Instruments Using MATLAB
(MATLAB)
5. Session 13b - Integrating GUI with Simulink execution (Part-II) (MATLAB)(Dec-2015)
(VJTILegend)
6. build a simulink model for TwinCat3-TE1400 matlab interface
(Rawl Group)

You might also like

Latest Posts

Article information

Author: Terrell Hackett

Last Updated: 09/19/2022

Views: 6245

Rating: 4.1 / 5 (52 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Terrell Hackett

Birthday: 1992-03-17

Address: Suite 453 459 Gibson Squares, East Adriane, AK 71925-5692

Phone: +21811810803470

Job: Chief Representative

Hobby: Board games, Rock climbing, Ghost hunting, Origami, Kabaddi, Mushroom hunting, Gaming

Introduction: My name is Terrell Hackett, I am a gleaming, brainy, courageous, helpful, healthy, cooperative, graceful person who loves writing and wants to share my knowledge and understanding with you.