Academic Block

Logo of Academicblock.net

Simulink in MATLAB

Simulink is an environment within MATLAB used for modeling, simulating, and analyzing dynamic systems. It provides a graphical interface for building models as block diagrams. This section introduces the basic concepts of Simulink and provides practical examples.

Getting Started with Simulink

To launch Simulink, use the following command in MATLAB:

% Launch Simulink
simulink

This will open the Simulink start page, where you can create new models or open existing ones.

Building Simple Models Using Simulink

Simulink allows users to create models by dragging blocks from libraries into the workspace. Here’s a basic example to create a model that solves the equation:

y = 2x2 + 3x + 5

Follow these steps:

  1. Drag a Constant block to represent input x.
  2. Add Gain, Sum, and Math Function blocks to calculate 2x2.
  3. Combine blocks to complete the equation.
  4. Use a Scope block to visualize the output.

Simulating the Model

Once the model is built, click the “Run” button in Simulink to simulate it. You can adjust parameters and observe the output in real-time.

Example 1: Creating Models of Dynamic Systems Using Block Diagrams in MATLAB

Dynamic systems can be effectively modeled using Simulink’s block diagram approach. This example demonstrates how to create and simulate a second-order mass-spring-damper system using Simulink.

System Description

The mass-spring-damper system is described by the following second-order differential equation:

m * d2x/dt2 + c * dx/dt + k * x = F(t)

Where:

  • m: Mass
  • c: Damping coefficient
  • k: Spring constant
  • F(t): Applied force
  • x: Displacement

Steps to Model the System

  1. Drag Blocks into the Workspace:
    • Use an Integrator block to represent dx/dt and another Integrator block for d2x/dt2.
    • Add Gain blocks for the coefficients m, c, and k.
    • Use Sum blocks to combine terms.
    • Add a Scope block to visualize the displacement x.
    • Use a Step block to model the force F(t).
  2. Connect the Blocks: Arrange and connect the blocks to represent the system’s differential equation.
  3. Set Parameters: Double-click on each block to set values for the coefficients m, c, k, and the step force magnitude.

MATLAB Commands to Automate Model Creation

Alternatively, you can create the Simulink model programmatically using MATLAB commands:

% Open a new Simulink model
new_system('mass_spring_damper');
open_system('mass_spring_damper');

% Add blocks
add_block('simulink/Sources/Step', 'mass_spring_damper/Step Force');
add_block('simulink/Commonly Used Blocks/Integrator', 'mass_spring_damper/Integrator1');
add_block('simulink/Commonly Used Blocks/Integrator', 'mass_spring_damper/Integrator2');
add_block('simulink/Commonly Used Blocks/Sum', 'mass_spring_damper/Sum1', 'Position', [200 200 250 250]);
add_block('simulink/Commonly Used Blocks/Gain', 'mass_spring_damper/Mass Gain');
add_block('simulink/Commonly Used Blocks/Gain', 'mass_spring_damper/Damping Gain');
add_block('simulink/Commonly Used Blocks/Gain', 'mass_spring_damper/Spring Gain');
add_block('simulink/Sinks/Scope', 'mass_spring_damper/Scope');

% Connect blocks
add_line('mass_spring_damper', 'Step Force/1', 'Sum1/1');
add_line('mass_spring_damper', 'Sum1/1', 'Mass Gain/1');
add_line('mass_spring_damper', 'Mass Gain/1', 'Integrator2/1');
add_line('mass_spring_damper', 'Integrator2/1', 'Integrator1/1');
add_line('mass_spring_damper', 'Integrator1/1', 'Scope/1');

% Set parameters
set_param('mass_spring_damper/Mass Gain', 'Gain', '1/m');
set_param('mass_spring_damper/Damping Gain', 'Gain', 'c');
set_param('mass_spring_damper/Spring Gain', 'Gain', 'k');

Simulating the Model

After building the model, simulate it using the following MATLAB commands:

% Simulate the system
sim('mass_spring_damper');

Output Visualization

The output from the Scope block will display the system’s response to the applied force over time. For example, a step force might result in a damped oscillatory response:

Time (s)    Displacement (x)

0           0
0.1         0.05
0.2         0.09
0.3         0.12
...
    

Example 2: Simulating Continuous, Discrete, and Hybrid Systems in MATLAB

Simulink allows for the simulation of continuous, discrete, and hybrid systems. This example illustrates a hybrid system combining continuous dynamics and discrete logic: a temperature control system with a heater that switches on or off based on a temperature threshold.

System Description

The hybrid temperature control system operates as follows:

  • Continuous Dynamics: Temperature changes over time due to heating and natural cooling.
  • Discrete Logic: A thermostat turns the heater on or off based on the current temperature.

The temperature dynamics are modeled by:

dT/dt = -k * (T - Tambient) + H * Q

Where:

  • T: Current temperature
  • Tambient: Ambient temperature
  • k: Cooling constant
  • H: Heater state (0 for off, 1 for on)
  • Q: Heating power

Steps to Model the System

  1. Continuous Dynamics: Use an Integrator block to model the temperature dynamics.
  2. Discrete Logic: Implement the thermostat logic using a Switch block and a Compare To Constant block.
  3. Visualize: Add a Scope block to observe temperature changes over time.

MATLAB Commands to Build the Model

The hybrid system can also be built programmatically using MATLAB commands:

% Open a new Simulink model
new_system('hybrid_system');
open_system('hybrid_system');

% Add blocks
add_block('simulink/Sources/Step', 'hybrid_system/Step Heater');
add_block('simulink/Commonly Used Blocks/Integrator', 'hybrid_system/Integrator');
add_block('simulink/Commonly Used Blocks/Gain', 'hybrid_system/Cooling Gain');
add_block('simulink/Logic and Bit Operations/Compare To Constant', 'hybrid_system/Thermostat');
add_block('simulink/Commonly Used Blocks/Switch', 'hybrid_system/Heater Switch');
add_block('simulink/Sinks/Scope', 'hybrid_system/Temperature Scope');

% Connect blocks
add_line('hybrid_system', 'Step Heater/1', 'Heater Switch/1');
add_line('hybrid_system', 'Heater Switch/1', 'Integrator/1');
add_line('hybrid_system', 'Integrator/1', 'Cooling Gain/1');
add_line('hybrid_system', 'Cooling Gain/1', 'Thermostat/1');
add_line('hybrid_system', 'Thermostat/1', 'Heater Switch/2');
add_line('hybrid_system', 'Integrator/1', 'Temperature Scope/1');

% Set parameters
set_param('hybrid_system/Cooling Gain', 'Gain', '-k');
set_param('hybrid_system/Thermostat', 'Const', 'Threshold');

Simulating the System

To simulate the model and observe the hybrid behavior:

% Simulate the hybrid system
sim('hybrid_system');

Output Visualization

The Scope block will display the temperature dynamics. The graph may show periods of heating and cooling based on the thermostat’s discrete logic:

Time (s)    Temperature (°C)

0           20
5           22
10          25
15          23
20          21
...
    

Example 3: Multidomain System Modeling in MATLAB

Simulink allows for the integration of electrical, mechanical, hydraulic, and thermal systems into a single model, enabling engineers to simulate complex multidomain interactions. This example demonstrates the modeling of an electric vehicle (EV) drivetrain system that combines these domains.

System Description

The electric vehicle system includes:

  • Electrical Domain: A battery powering an electric motor.
  • Mechanical Domain: The drivetrain transmitting torque to the wheels.
  • Hydraulic Domain: Braking system using hydraulic pressure.
  • Thermal Domain: Thermal effects on the battery and motor due to power dissipation.

Steps to Model the System

  1. Electrical Subsystem: Model the battery and motor using Simulink blocks from the Simscape Electrical library.
  2. Mechanical Subsystem: Use Simscape Multibody components to model the drivetrain and wheel dynamics.
  3. Hydraulic Subsystem: Implement a braking system using Simscape Fluids.
  4. Thermal Subsystem: Use thermal blocks to represent heat dissipation in the battery and motor.

MATLAB Commands to Build the Model

The EV drivetrain model can be constructed programmatically:

% Create a new Simulink model
new_system('EV_Drivetrain');
open_system('EV_Drivetrain');

% Add Electrical Subsystem
add_block('simscape/Electrical/Electrical Sources/DC Voltage Source', 'EV_Drivetrain/Battery');
add_block('simscape/Electrical/Electrical Machines/Permanent Magnet Synchronous Motor', 'EV_Drivetrain/Motor');
add_line('EV_Drivetrain', 'Battery/1', 'Motor/1');

% Add Mechanical Subsystem
add_block('simscape/Multibody/Revolute Joint', 'EV_Drivetrain/Wheel Joint');
add_block('simscape/Multibody/Inertia', 'EV_Drivetrain/Wheel Inertia');
add_line('EV_Drivetrain', 'Motor/1', 'Wheel Joint/1');
add_line('EV_Drivetrain', 'Wheel Joint/1', 'Wheel Inertia/1');

% Add Hydraulic Subsystem
add_block('simscape/Fluids/Hydraulic Sources/Constant Pressure Source', 'EV_Drivetrain/Brake Pressure');
add_block('simscape/Fluids/Directional Control Valves/3-Way Valve', 'EV_Drivetrain/Brake Valve');
add_line('EV_Drivetrain', 'Brake Pressure/1', 'Brake Valve/1');

% Add Thermal Subsystem
add_block('simscape/Foundation Library/Thermal Elements/Convection', 'EV_Drivetrain/Thermal Convection');
add_block('simscape/Foundation Library/Thermal Elements/Thermal Mass', 'EV_Drivetrain/Thermal Mass');
add_line('EV_Drivetrain', 'Motor/1', 'Thermal Convection/1');
add_line('EV_Drivetrain', 'Thermal Convection/1', 'Thermal Mass/1');

% Set block parameters
set_param('EV_Drivetrain/Battery', 'Amplitude', '400'); % Set battery voltage
set_param('EV_Drivetrain/Motor', 'RatedSpeed', '3000'); % Set motor speed

Simulating the System

Run the simulation to observe the interactions between subsystems:

% Simulate the EV drivetrain system
sim('EV_Drivetrain');

Output Visualization

Simulation results will include:

  • Electrical: Battery voltage and motor current.
  • Mechanical: Torque and rotational speed of the wheels.
  • Hydraulic: Brake pressure over time.
  • Thermal: Heat dissipation in the motor and battery.
Time (s)    Motor Speed (rpm)    Torque (Nm)    Battery Voltage (V)    Heat Dissipation (W)

0           0                      0             400                    0
1           500                    150           390                    20
2           1500                   200           380                    40
3           3000                   250           370                    60
...
    

Example 4: Model and Simulate Embedded Software in MATLAB

Embedded software design and simulation is a crucial part of developing real-time systems such as controllers and processors. MATLAB and Simulink provide tools for designing, verifying, and generating embedded software. This example demonstrates how to model and simulate a PID controller for a DC motor system.

System Description

The system consists of a DC motor, modeled in Simulink, controlled by embedded software implementing a PID (Proportional-Integral-Derivative) control algorithm. The software runs on a simulated microcontroller environment.

Steps to Model the System

  1. Create the Plant Model: Use Simulink blocks to model the dynamics of the DC motor.
  2. Design the Controller: Implement the PID controller logic in MATLAB function blocks.
  3. Integrate with Embedded Software: Simulate the software logic and test its interaction with the plant.

MATLAB Commands to Build the Model

The model is created programmatically as follows:

% Create a new Simulink model
new_system('EmbeddedControlSystem');
open_system('EmbeddedControlSystem');

% Add Plant Model: DC Motor
add_block('simulink/Continuous/Transfer Fcn', 'EmbeddedControlSystem/DC Motor');
set_param('EmbeddedControlSystem/DC Motor', 'Numerator', '[1]', 'Denominator', '[1 10 20]');

% Add Controller: PID Logic
add_block('simulink/User-Defined Functions/MATLAB Function', 'EmbeddedControlSystem/PID Controller');
set_param('EmbeddedControlSystem/PID Controller', 'MATLABFcn', 'PIDControllerLogic');

% Add Input and Output
add_block('simulink/Sources/Step', 'EmbeddedControlSystem/Step Input');
add_block('simulink/Sinks/Scope', 'EmbeddedControlSystem/Output Scope');
add_line('EmbeddedControlSystem', 'Step Input/1', 'PID Controller/1');
add_line('EmbeddedControlSystem', 'PID Controller/1', 'DC Motor/1');
add_line('EmbeddedControlSystem', 'DC Motor/1', 'Output Scope/1');

% Define PID Controller Logic in MATLAB Function
function u = PIDControllerLogic(e)
persistent integral prevError;
if isempty(integral), integral = 0; prevError = 0; end
kp = 1; ki = 0.1; kd = 0.05; % PID coefficients
integral = integral + e;
derivative = e - prevError;
u = kp * e + ki * integral + kd * derivative;
prevError = e;
end

Simulating the System

Run the simulation to observe the PID controller’s behavior:

% Run simulation
sim('EmbeddedControlSystem');

Output Visualization

The results show the system’s response to a step input and the performance of the PID controller:

Time (s)    Step Input     Motor Speed (RPM)
0           0              0
0.5         10             5
1.0         10             8
2.0         10             10
...
    

Example 5: Simulate Neural Networks Using Simulink in MATLAB

Simulink offers a powerful environment to model and simulate neural networks for various applications such as control, signal processing, and pattern recognition. This example demonstrates the simulation of a feedforward neural network for function approximation.

System Description

The neural network is trained to approximate a nonlinear function: y = sin(2 * x). The network consists of:

  • An input layer with one neuron.
  • A hidden layer with ten neurons using the sigmoid activation function.
  • An output layer with one neuron using a linear activation function.

Steps to Build and Simulate the Neural Network

  1. Create the Neural Network: Use MATLAB to design and train the neural network.
  2. Integrate with Simulink: Export the trained network to Simulink using a Neural Network block.
  3. Simulate the Network: Evaluate its performance on a test dataset.

MATLAB Commands to Train the Network

The neural network is trained as follows:

% Generate training data
x = linspace(-1, 1, 100);
y = sin(2 * pi * x);

% Create and train a neural network
net = feedforwardnet(10); % Network with 10 hidden neurons
net = train(net, x, y);

% Test the network
x_test = linspace(-1.5, 1.5, 50);
y_test = net(x_test);

% Export the network to Simulink
gensim(net);

Integrating the Network into Simulink

When you execute gensim(net), MATLAB automatically creates a Simulink model with the neural network block integrated. You can then use this block in a larger Simulink system model.

Simulink Model Configuration

To test the neural network in Simulink:

  1. Open the generated Simulink model.
  2. Connect the input to a sine wave block to simulate the testing data.
  3. Connect the output to a scope block to visualize the network’s predictions.

The Simulink model will look like this:

[Input (Sine Wave)] ---> [Neural Network Block] ---> [Scope]
    

Simulating the Model

Run the Simulink model to observe the neural network’s performance. The output is visualized in the Scope block, showing how well the network approximates the target function.

MATLAB Code to Visualize Results

% Plot the results
plot(x, y, 'r', 'DisplayName', 'Target'); % Training data
hold on;
plot(x_test, y_test, 'b', 'DisplayName', 'Neural Network Output'); % Test results
legend;
xlabel('Input x');
ylabel('Output y');
title('Neural Network Function Approximation');
grid on;

Output Visualization

The neural network output closely matches the target function:

Target:        y = sin(2 * pi * x)

Neural Output: y ≈ sin(2 * pi * x)
    

Commonly Used Blocks in Simulink

Block
Description
Constant
Represents a constant input to the system.
Gain
Multiplies the input by a specified value.
Scope
Visualizes the output of the simulation.
Sum
Performs addition or subtraction on inputs.
Math Function
Applies mathematical functions such as square or square root.
Embedded Coder
Generates optimized C/C++ code for embedded processors.
feedforwardnet
Creates a feedforward neural network.
train
Trains the neural network using training data.
gensim
Generates a Simulink model of the trained neural network.
sim
Simulates the neural network.
Integrator
Calculates the integral of the input over time.

Practice Problem

Test Yourself

1. Analyze the behavior of the mass-spring-damper system for varying damping coefficients c.

2. Simulate the hybrid system with a variable heating power Q.

3. Add regenerative braking to the model. Observe how it affects the battery voltage.

4. Use Simulink Coder to generate code for the PID controller and deploy it to a microcontroller.

5. Train the network on a different function (e.g., y = cos(2 * x)) and test its performance.