You are on page 1of 21

CHAPTER - 3

MATLAB & SIMULINK

3.1 MATLAB

MATLAB is a high-performance language for technical computing. It integrates


computation, visualization, and programming in an easy-to-use environment where problems and
solutions are expressed in familiar mathematical notation. Typical uses include

• Math and computation


• Algorithm development
• Data acquisition
• Modeling, simulation, and prototyping
• Data analysis, exploration, and visualization
• Scientific and engineering graphics
• Application development, including graphical user interface building

MATLAB is an interactive system whose basic data element is an array that does not
require dimensioning. This allows you to solve many technical computing problems, especially
those with matrix and vector formulations, in a fraction of the time it would take to write a
program in a scalar non interactive language such as C or FORTRAN.

The name MATLAB stands for matrix laboratory. MATLAB was originally written to
provide easy access to matrix software developed by the LINPACK and EISPACK projects.
MATLAB has evolved over a period of years with input from many users. In university
environments, it is the standard instructional tool for introductory and advanced courses in
mathematics, engineering, and science. In industry, MATLAB is the tool of choice for high-
productivity research, development, and analysis.

MATLAB features a family of add-on application-specific solutions called tool boxes.


Very important to most users of MATLAB, toolboxes allow you to learn and apply specialized
technology. Tool boxes are comprehensive collections of MATLAB functions (M-files) that
extend the MATLAB environment to solve particular classes of problems.

3.2 SIMULINK

Simulink (Simulation and Link) is an extension of MATLAB by Mathworks Inc. It works


with MATLAB to offer modelling, simulating, and analyzing of dynamical systems under a
graphical user interface (GUI) environment. The construction of a model is simplified with click-
and-drag mouse operations. Simulink includes a comprehensive block library of toolboxes for
both linear and nonlinear analyses. Models are hierarchical, which allow using both top-down
and bottom-up approaches. As Simulink is an integral part of MATLAB, it is easy to switch back
and forth during the analysis process and thus, the user may take full advantage of features
offered in both environments. Simulink can be used to explore the behavior of a wide range of
real-world dynamic systems, including electrical circuits, shock absorbers, braking systems, and
many other electrical, mechanical, and thermodynamic systems.

Simulink encourages one to try things out. One can easily build models from scratch, or
take an existing model and add to it. Simulations are interactive, so you can change parameters
on the fly and immediately see what happens. This has instant access to all the analysis tools in
MATLAB, so you can take the results and analyze and visualize them. A goal of Simulink is to
give you a sense of the fun of modeling and simulation, through an environment that encourages
you to pose a question, model it, and see what happens.

With Simulink, one can move beyond idealized linear models to explore more realistic
nonlinear models, factoring in friction, air resistance, gear slippage, hard stops, and the other
things that describe real-world phenomena. Simulink turns your computer into a lab for modeling
and analyzing systems that simply wouldn't be possible or practical otherwise, whether the
behavior of an automotive clutch system, the flutter of an airplane wing, the dynamics of a
predator-prey model, or the effect of the monetary supply on the economy.

3.2.1 Modeling Dynamic Systems


A Simulink block diagram model is a graphical representation of a mathematical model of a
dynamic system. A mathematical model of a dynamic system is described by a set of equations.
The mathematical equations described by a block diagram model are known as algebraic,
differential, and/or difference equations.

Alternatively, one can hit the New Simulink Model button at the top of the MATLAB
command window as shown below:

When it starts, Simulink brings up two windows. The first is the main Simulink window,
which appears as:

The second window is a blank, untitled, model window. This is the window into which a
new model can be drawn.

3.2.2 Basic Elements


There are two major classes of items in Simulink: blocks and lines. Blocks are used to
generate, modify, combine, output, and display signals. Lines are used to transfer signals from
one block to another.
Blocks: There are several general classes of blocks:
• Sources: Used to generate various signals
• Sinks: Used to output or display signals
• Discrete: Linear, discrete-time system elements (transfer functions, state-space
models, etc.)
• Linear: Linear, continuous-time system elements and connections (summing
junctions, gains, etc.)
• Nonlinear: Nonlinear operators (arbitrary functions, saturation, delay, etc.)
• Connections: Multiplex; Demultiplex, System Macros, etc.
Blocks have zero to several input terminals and zero to several output terminals. Unused
input terminals are indicated by a small open triangle. Unused output terminals are indicated
by a small triangular point. The block shown below has an unused input terminal on the left
and an unused output terminal on the right.

3.2.3 Lines
Lines transmit signals in the direction indicated by the arrow. Lines must always transmit
signals from the output terminal of one block to the input terminal of another block. On
exception to this is a line can tap off of another line, splitting the signal to each of two
destination blocks, as shown below (click the figure to download the model file called
split.mdl).

Lines can never inject a signal into another line; lines must be combined through the use
of a block such as a summing junction. It is determined by the blocks on either end of the line.
3.2.4 Simple Example

The simple model


(from the model file section) consists of three blocks: Step, Transfer Fcn, and Scope. The Step is
a source block from which a step input signal originates. This signal is transferred through the
line in the direction indicated by the arrow to the Transfer Function linear block. The Transfer
Function modifies its input signal and outputs a new signal on a line to the Scope. The Scope is a
sink block used to display a signal much like an oscilloscope.

3.2.5 Modifying Blocks

A block can be modified by double-clicking on it. For example, if you double-click on the
"Transfer Fcn" block in the simple model, you will see the following dialog box.

This dialog box contains fields for the numerator and the denominator of the block's
transfer function. By entering a vector containing the coefficients of the desired numerator or
denominator polynomial, the desired transfer function can be entered. For example, to change the
denominator to s^2+2s+1, enter the following into the denominator field: [1 2 1] and hit the close
button, the model window will change to the following, which reflects the change in the
denominator of the transfer function.
The

3.2.6 Running Simulations


To run a simulation, we will work with the following model file:
Before running a simulation of this system, first open the scope window by double-
clicking on the scope block. Then, to start the simulation, either select Start from the
Simulation menu (as shown below) or hit Ctrl-T in the model window.

The simulation should run very quickly and the scope window will appear as shown
below.
Note that the simulation output (shown in yellow) is at a very low level relative to the
axes of the scope. To fix this, hit the auto-scale button (binoculars), which will rescale the axes
as shown below.

Note that the step response does not begin until t=1. This can be changed by double-
clicking on the "step" block. Now, we will change the parameters of the system and simulate
the system again. Double-click on the "Transfer Fcn" block in the model window and change
the denominator to [1 20 400]

Re-run the simulation (hit Ctrl-T) and you should see what appears as a flat line in the
scope window. Hit the autoscale button, and you should see the following in the scope
window.
Notice that the auto scale button only changes the vertical axis. Since the new transfer
function has a very fast response, it is compressed into a very narrow part of the scope window.
This is not really a problem with the scope, but with the simulation itself. Simulink simulated
the system for a full ten seconds even though the system had reached steady state shortly after
one second. To correct this, you need to change the parameters of the simulation itself. In the
model window, select Parameters from the Simulation menu. You will see the following
dialog box.

3.3 Simulink Basics Tutorial - Interaction with MATLAB

We will examine three of the ways in which Simulink can interact with MATLAB.

• Block parameters can be defined from MATLAB variable.

• Signals can be exchanged between Simulink and MATLAB.

• Entire systems can be extracted from Simulink into MATLAB.

3.3.1 Taking Variables from MATLAB

In some cases, parameters, such as gain, may be calculated in MATLAB to be used in a


Simulink model. If this is the case, it is not necessary to enter the result of the MATLAB
calculation directly into Simulink. For example, suppose we calculated the gain in MATLAB
in the variable K. Emulate this by entering the following command at the MATLAB command
prompt.

K=2.5
This variable can now be used in the Simulink Gain block. In your simulink model,
double-click on the Gain block and enter the following in the Gain field.

Close this dialog box. Notice now that the Gain block in the Simulink model shows the
variable K rather than a number.

Now, you can re-run the simulation and view the output on the Scope. The result should
be the same as before.

Now, if any calculations are done in MATLAB to change any of the variab used in the
Simulink model, the simulation will use the new values the next time it is run. To try this, in
MATLAB, change the gain, K, by entering the following at the command prompt.
K=5
Start the Simulink simulation again, bring up the Scope window, and hit the autoscale
button. You will see the following output which reflects the new, higher gain.

Simulink is a platform for multinomial simulation and Model-Based Design for


dynamic systems. It provides an interactive graphical environment and a customizable set of
block libraries, and can be extended for specialized applications.

3.4 Some Tool Boxes of MATLAB

3.4.1 Real-Time Workshop

Real-Time Workshop generates and executes stand-alone C code for developing


and testing algorithms modeled in Simulink. The resulting code can be used for many real-time
and non-real-time applications, including simulation acceleration, rapid prototyping, and
hardware-in-the-loop testing. You can interactively tune and monitor the generated code using
Simulink blocks and built-in analysis capabilities, or run and interact with the code outside the
MATLAB and Simulink environment.

3.4.2 SimDriveline

SimDriveline extends Simulink with tools for modeling and simulating the
mechanics of driveline (drive-train) systems. These tools include components such as gears,
rotating shafts, and clutches; standard transmission templates; and engine and tire models.
SimDriveline is optimized for ease of use and speed of calculation for driveline mechanics.

3.4.3 SimMechanics
SimMechanics extends Simulink with tools for modeling and simulating mechanical
systems. It is integrated with MathWorks control design and code generation products, enable
to design and test in real time with the model of the mechanical system.

3.4.4 SimPowerSystems

SimPowerSystems extends Simulink with tools for modeling and simulating basic
electrical circuits and detailed electrical power systems. These tools let you model the
generation, transmission, distribution, and consumption of electrical power, as well as its
conversion into mechanical power. SimPowerSystems is well suited to the development of
complex, self-contained power systems, such as those in automobiles, aircraft, manufacturing
plants, and power utility applications.

3.4.5 Simulink Control Design

Simulink Control Design provides advanced functionality for performing linear


analysis of nonlinear models. You can extract linear approximations of a model to analyze
characteristics such as time and frequency responses and pole-zero dynamics.

3.4.6 Simulink Accelerator

The Simulink Accelerator increases the simulation speed of model by accelerating model
execution.

3.4.7 Simulink Report Generator

The Simulink Report Generator automatically creates documentation from


Simulink and State flow models. You can document software requirements and design
specifications and produce reports from your models, all in a standard format. You can use the
pre built templates or create a template that incorporates your own styles and standards.

3.5 FUZZY LOGIC

Fuzzy logic systems have been praived to be universal approximators and hence these are
good candidates for solving complex control problems. Some of the advantages of fuzzy logic
are that they are nonlinear, adaptive, can admit a high degree of parallel implementation, and can
tolerate uncertainty in the system. More importantly, certain aspects of the skill of process
operators can be incorporated into the design of an FLS. Such information can furtlier be refined
based on the performance of the system. FLC will be used to denote fuzzy logic control or fuzzy
logic controller. An FLC is easy to design if sufficient process knowledge is available.

3.5.1 Fuzzy Logic Controller (FLC)

FLC incorporates a simple, rule-based IF X AND Y THEN Z approach to a solving


control problem rather than attempting to model a system mathematically. The FLC model is
empirically-based, relying on an operator's experience rather than their technical understanding
of the system. For example, rather than dealing with temperature control in terms such as "SP
=500F", "T <1000F", or "210C <TEMP <220C", terms like "IF (process is too cool) AND
(process is getting colder) THEN (add heat to the process)" or "IF (process is too hot) AND
(process is heating rapidly) THEN (cool the process quickly)" are used. These terms are
imprecise and yet very descriptive of what must actually happen. Consider what you do in the
shower if the temperature is too cold, you will make the water comfortable very quickly with
little trouble. FLC is capable of mimicking this type of behavior but at very high rate. Block
diagram of fuzzy controller is given as under. The Fuzzy Logic Controller block implements a
fuzzy inference system.

Fig. Block diagram of fuzzy controller


Figure. Block parameters

After making the appropriate rules for the controller to work it is then saved in the under shown
dialog box. To open the dialog box for the Fuzzy Logic Controller (with or without the Rule
Viewer), double-click the block. Enter the name of the structure variable describing your FIS.
This variable must be located in the MATLAB workspace. If the fuzzy inference system has
multiple inputs, these inputs should be multiplexed together before feeding them into either the
Fuzzy Logic Controller or the Fuzzy Logic Controller with Rule Viewer block. Similarly, if the
system has multiple outputs, these signals will be passed out of the block on one multiplexed
line.

(FLS) is the building block in most systems incorporating fuzzy logic. An FLC can be
implemented in the form of an FLS. One form of an FLC consists of a fuzzifier, a rule base, an
inference engine and a defuzzifier.First rule is made according to desired output then it is save in
the above FIS file.

3.5.2 Structure of Fuzzy Controller


Fuzzy controller is the main block where the entire control action is being taken. There
are specific components characteristic of a fuzzy controller to support a design procedure. The
controller is between a preprocessing block and a post-processing block. The main blocks of
fuzzy controller are:
• Fuzzification.
• Rule base.
• Inference engine.
• Defuzzification.

Fig. Blocks of a fuzzy controller


3.5.2.1 Preprocessing

The inputs are most often hard or crisp measurements from some measuring equipment,
Rather than linguistic. A preprocessor, the first block in Fig. 1.4, conditions the measurements
before they enter the controller. Examples of preprocessing are:

• Quantization in connection with sampling or rounding to integers;


• Normalization or scaling onto a particular, standard range;
• Filtering in order to remove noise;
• Averaging to obtain long term or short term tendencies;
• A combination of several measurements to obtain key indicators; and
• Differentiation and integration or their discrete equivalences.

Preprocessing consists of a linear or non-linear scaling as well as a quantisation in case


the membership functions are discretised (vectors); if not, the membership of the input can just
be looked up in an appropriate function.

When the input to the controller is error, the control strategy is a static mapping between
input and control signal. A dynamic controller would have additional inputs, for example
derivatives, integrals, or previous values of measurements backwards in time. These are created
in the preprocessor thus making the controller multi-dimensional, which requires many rules and
makes it more difficult to design. The preprocessor then passes the data on to the controller.

3.5.2.2. Fuzzification
The first block inside the controller is Fuzzification, which converts each piece of input
data to degrees of membership by a lookup in one or several membership functions. The
fuzzification block thus matches the input data with the conditions of the rules to determine how
well the condition of each rule matches that particular input instance. There is a degree of
membership for each linguistic term that applies to that input variable.

3.5.2.3 Rule Base

The collection of rules is termed as ruse base. Rules are written in order for control of the
control signal. The rules may use several variables both in the condition and the conclusion of
the rules. The controllers can therefore be applied to both multi-input-multi-output (MIMO)
problems and single-input-single-output (SISO) problems. The typical SISO problem is to
regulate a control signal based on an error signal. The controller may actually need both the
error, the change in error and the accumulated error as inputs, but we will call it single-loop
control, because in principle all three are formed from the error measurement. To simplify, this
section assumes that the control objective is to regulate some process output around a prescribed
set point or reference. The presentation is thus limited to single-loop control. When designing the
rule base, the designer needs to consider the number of term sets, their shape, and their overlap.

3.5.2.4 Rule formats

This is helpful in framing the rules. Basically a linguistic controller contains rules in the
if-then format, but they can be presented in different formats. In many systems, the rules are
presented to the end-user in a format similar to the one below,

1. If error is Neg and change in error is Neg then output is NB

2. If error is Neg and change in error is Zero then output is NM


3. If error is Neg and change in error is Pos then output is Zero
4. If error is Zero and change in error is Neg then output is NM

The names Zero, Pos, Neg are labels of fuzzy sets as well as NB, NM, PB and PM
(Negative big, negative medium, positive big and positive medium respectively). Another way of
framing the rules is relational format. It is a more compact way of representation. When the
input variables are error and change in error, as they are here, that format is also called a
linguistic variable. In case there are n > 5 input variables involved, the table grows to an n-
dimensional array; rather user-unfriendly. To accommodate several outputs, a nested
arrangement is conceivable. A rule with several outputs could also be broken down into several
rules with one output. Several key words are used in framing the rules. These are explained
below.

3.6 Membership Functions

Every element in the universe of discourse is a member of a Fuzzy set to some grade, maybe
even zero. The grade of membership for all its members describes a fuzzy set, such as Neg. In
fuzzy sets elements are assigned a grade of membership, such that the transition from
membership to non-membership is gradual rather than abrupt. The set of elements that have a
non-zero membership is called the Support of the Fuzzy set. The function that ties a number to
each element x of the universe is called the Membership function µ(x).

Building a fuzzy set is of prominent.

According to fuzzy set theory the choice of the shape and width is subjective, but a few rules of
thumb apply.

 A term set should be sufficiently wide to allow for noise in the measurement.

 A certain amount of overlap is desirable; otherwise the controller may run into poorly
defined states, where it does not return a well-defined output.

The manual for building a fuzzy set is:

 Start with triangular sets: All membership functions for a particular input or output
should be symmetrical triangles of the same width. The leftmost and the rightmost should
be shouldered ramps.

 The over lap should be at least 50%: The widths should initially be chosen so that each
value of the universe is a member of at least two sets, except possibly for elements at the
extreme ends. If, on the other hand, there is a gap between two sets no rules fire for
values in the gap. Consequently the controller function is not defined.

Membership functions can be flat on the top, piece-wise linear and triangle shaped, rectangular,
or ramps with horizontal shoulders.

Some typical shapes of membership functions are shown below:

Fig. Examples of membership functions.(a) s-function, (b) ∏- function, (c) z-function, (d-f)
triangular versions, (g-i) trapezoidal versions, (j) flat ∏- function, (k) rectangle, (l) singleton.
A single pair (x, µ(x)) is a fuzzy singleton; singleton output means replacing the fuzzy
sets in the conclusion by numbers (scalars).
For example: If error is Pos then output is 10 volts
There are at least three advantages to this:
 The computations are simpler;
 it is possible to drive the control signal to its extreme values; and
 it may actually be a more intuitive way to write rules.

3.7 Inference Engine

The rules reflect the strategy that the control signal should be a combination of
the reference error and the change in error, a fuzzy proportional-derivative controller. For each
rule, the inference engine looks up the membership values in the condition of the rule.
3.8 Defuzzification

The resulting fuzzy set must be converted to a number that can be sent to the process as a
control signal. This operation is called defuzzification, and in Fig. the x-coordinate marked by a
white, vertical dividing line becomes the control signal. The resulting fuzzy set is thus
defuzzified into a crisp control signal. There are several defuzzification methods.

 Centre of gravity (COG):

The crisp output value x is the abscissa under the centre of gravity of the
fuzzy set,

Here xi is a running point in a discrete universe, and µ (xi) is its membership value in the
membership function. The expression can be interpreted as the weighted average of the elements
in the support set. For the continuous case, replace the summations by integrals. It is a much-
used method although its computational complexity is relatively high. This method is also called
centroid of area.

 Centre of gravity method for singletons (COGS):

If the membership functions of the conclusions are singletons, the output value is

Here si is the position of singleton i in the universe, and µ (si), is equal to the firing
strength of rule i. This method has a relatively good computational complexity, and x is
differentiable with respect to the singletons si, which is useful in neurofuzzy systems.

 Bisector of area (BOA):


This method picks the abscissa of the vertical line that divides the area
under the curve in two equal halves. In the continuous case,

Here x is the running point in the universe, µ(x) is its membership, Min is the leftmost value of
the universe and Max is the rightmost value. Its computational complexity is relatively high, and
it can be ambiguous. For example, if the fuzzy set consists of two Singletons any point between
the two would divide the area in two halves; consequently it is safer to say that in the discrete
case, BOA is not defined.

 Mean of maxima (MOM):

An intuitive approach is to choose the point with the strongest possibility,


i.e. maximal membership. This method disregards the shape of the fuzzy set, but the
computational complexity is relatively good.

 Left most maxima (LM), and Right most maxima (RM):

Another possibility is to choose the leftmost maximum (LM), or the


rightmost maximum (RM). In the case of a Robot, for instance, it must choose between left or
right to avoid an obstacle in front of it. The defuzzifier must then choose one or the other, not
something in between.

3.9 Postprocessing

Output scaling is also relevant. In case the output is defined on a standard universe this must be
scaled to engineering units. The postprocessing unit does this function. For instance, volts,
meters, or tons per hour. An example is the scaling from the standard universe [-1, 1] to the
physical units [-10, 10] volts. The postprocessing block often contains an output gain that can be
tuned, and sometimes also an integrator.

The following is a checklist of design choices that have to be made:


o Rule base related choice: Number of inputs and outputs, rules, universes,
continuous /discrete, the number of membership functions, their overlap and width,
singleton output;
o Inference engine related choice: Connectives, modifiers, activation operation,
aggregation operation, and accumulation operation.
o Defuzzification method: COG, COGS, BOA, MOM, LM, and RM.
o Pre-and post-processing: Scaling, gain factors, quantisation, and sampling time.

Some of these items must always be considered, others may not play a role in the
particular design. The linear fuzzy controller may be used in a design procedure based on PID
control:

1. Tune a PID controller.


2. Replace it with a linear fuzzy controller.
3. Transfer gains.
4. Make the fuzzy controller nonlinear.
5. Fine-tune it.
It seems sensible to start the controller design with a crisp PID controller, maybe even just a P
controller, and get the system stabilized. From there it is easier to go to fuzzy control.

You might also like