Sie sind auf Seite 1von 28

LAB-3 INTRODUCTION TO MATL AB & SIMULINK

MATLAB BASICS TUTORIAL

Key MATLAB Commands used in this tutorial are:


1.
2.
3.
4.
5.
6.
7.
8.

plot
polyval
roots
conv
deconv
inv
eig
poly

MATLAB is an interactive program for numerical computation and data visualization; it is used
extensively by control engineers for analysis and design. There are many different toolboxes
available which extend the basic functions of MATLAB into different application areas; in these
tutorials, we will make extensive use of the Control Systems Toolbox.
Note: The idea behind these tutorials is that you can view them in one window while
running MATLAB in another window. You should be able to re-do all of the plots and
calculations in the tutorials by cutting and pasting text from the tutorials into MATLAB or
an m-file.
VECTORS

Let's start off by creating something simple, like a vector. Enter each element of the vector
(separated by a space) between brackets, and set it equal to a variable. For example, to create the
vector a, enter into the MATLAB command window.
a = [1 2 3 4 5 6 9 8 7]
MATLAB should return:
a=
1 2 3 4 5 6 9 8 7
1|P a g e

Let's say you want to create a vector with elements between 0 and 20 evenly spaced in
increments of 2 (this method is frequently used to create a time vector):
t = 0:2:20

t=
0 2 4 6 8 10 12 14 16 18 20
Manipulating vectors is almost as easy as creating them. First, suppose you would like to add 2
to each of the elements in vector 'a'. The equation for that looks like:
b=a+2

b=
3 4 5 6 7 8 11 10 9
Now suppose, you would like to add two vectors together. If the two vectors are the same length,
it is easy. Simply add the two as shown below:
c=a+b

c=
4 6 8 10 12 14 20 18 16
Subtraction of vectors of the same length works exactly the same way.

2|P a g e

FUNCTIONS

To make life easier, MATLAB includes many standard functions. Each function is a block of code
that accomplishes a specific task. MATLAB contains all of the standard functions such as sin, cos,
log, exp, sqrt, as well as many others. Commonly used constants such as pi, and i or j for the
square root of -1, are also incorporated into MATLAB.
sin(pi/4)
ans =
0.7071

To determine the usage of any function, type help [function name] at the MATLAB command
window.
PLOTTING

It is also easy to create plots in MATLAB. Suppose you wanted to plot a sine wave as a function
of time. First make a time vector (the semicolon after each statement tells MATLAB we don't
want to see all the values) and then compute the sin value at each time.
>> t=0:0.1:20;
>> y=sin(t);
>> plot(t, y);
>> title ('sine wave as a function of time')
>> xlabel('time')
>> ylabel('voltage')

3|P a g e

POLYNOMIALS

In MATLAB, a polynomial is represented by a vector. To create a polynomial in MATLAB, simply


enter each coefficient of the polynomial into the vector in descending order. For instance, let's
say you have the following polynomial:

>> x=[1 3 -15 -2 9]

x=

3 -15 -2

MATLAB can interpret a vector of length n+1 as an nth order polynomial. Thus, if your
polynomial is missing any coefficients, you must enter zeros in the appropriate place in the
vector. For example,

would be represented in MATLAB as:


>> y=[1 0 0 0 1]

y =

You can find the value of a polynomial using the polyval function. For example, to find the
value of the above polynomial at s=2,
>> polyval(y,2)
ans =
17

You can also extract the roots of a polynomial. This is useful when you have a high-order
polynomial such as the previous X and Y polynomials:

Finding the roots would be as easy as entering the following command;


4|P a g e

>> roots(x)

ans =

-5.5745
2.5836
-0.7951
0.7860

>> roots(y)

ans =

-0.7071 + 0.7071i
-0.7071 - 0.7071i
0.7071 + 0.7071i
0.7071 - 0.7071i

Let's say you want to multiply two polynomials together. The product of two polynomials is
found by taking the convolution of their coefficients. MATLAB's function conv that will do this
for you.
>> conv(x,y)

ans =

3 -15

-2

10

3 -15

-2

9
5|P a g e

To double check the result, try to find the roots of the convolution, you should get all the roots
you found earlier:
>> roots(conv(x,y))
ans =

-5.5745
2.5836
-0.7071 + 0.7071i
-0.7071 - 0.7071i
-0.7951
0.7071 + 0.7071i
0.7071 - 0.7071i
0.7860
Dividing two polynomials is just as easy. The deconv function will return the remainder as well
as the result. Let's divide convolution result of the two polynomials [x,y] by y and see if we get
x.
>> [XX, R]=deconv((conv(x,y)),y)

XX =

3 -15

-2

R=
0

>> XX-x
ans =
0

6|P a g e

MATRICES

Entering matrices into MATLAB is the same as entering a vector, except each row of elements is
separated by a semicolon (;) or a return:
B = [1 2 3 4;5 6 7 8;9 10 11 12]
B =
1
5
9

2
6
10

3
7
11

4
8
12

3
7
11

4
8
12

B = [ 1 2 3 4
5 6 7 8
9 10 11 12]
B =
1
5
9

2
6
10

Matrices in MATLAB can be manipulated in many ways. For one, you can find the transpose of
a matrix using the apostrophe key:
C = B'
C =
1
2
3
4

5
6
7
8

9
10
11
12

It should be noted that if C had been complex, the apostrophe would have actually given the
complex conjugate transpose. To get the transpose, use .' (the two commands are the same if the
matrix is not complex).
Now you can multiply the two matrices B and C together. Remember that order matters when
multiplying matrices.
D = B * C
D =
30
70
110
D

70
174
278

110
278
446

122
140
158
176

137
158
179
200

= C * B
D =
107
122
137
152

152
176
200
224

7|P a g e

Another option for matrix manipulation is that you can multiply the corresponding elements of
two matrices using the .* operator (the matrices must be the same size to do this).
E = [1 2;3 4]
F = [2 3;4 5]
G = E .* F
E =
1
3

2
4

2
4

3
5

2
12

6
20

F =

G =

If you have a square matrix, like E, you can also multiply it by itself as many times as you like
by raising it to a given power.
E^3
ans =
37
81

54
118

If wanted to cube each element in the matrix, just use the element-by-element cubing.
E.^3
ans =
1
27

8
64

You can also find the inverse of a matrix:


X = inv(E)
X =
-2.0000
1.5000

1.0000
-0.5000

or its eigenvalues:
eig(E)
ans =
-0.3723
5.3723

8|P a g e

There is even a function to find the coefficients of the characteristic polynomial of a matrix. The
"poly" function creates a vector that includes the coefficients of the characteristic polynomial.
p = poly(E)
p =
1.0000

-5.0000

-2.0000

Remember that the eigenvalues of a matrix are the same as the roots of its characteristic
polynomial:
roots(p)
ans =
5.3723
-0.3723

9|P a g e

EXERCISE 1
MATLAB MODELING TUTORIAL

MATLAB can be used to represent a physical system or a model. In this tutorial, you will learn
how to enter a differential equation model into MATLAB. Let's start with a review of how to
represent a physical system as a set of differential equations.
TRAIN SYSTEM

In this example, we will consider a toy train consisting of an engine and a car. Assuming that the
train only travels in one direction, we want to apply control to the train so that it has a smooth
start-up and stop, along with a constant-speed ride.
The mass of the engine and the car will be represented by M1 and M2, respectively. The two are
held together by a spring, which has the stiffness coefficient of k. F represents the force applied
by the engine, and the Greek letter, mu (which will also be represented by the letter u), represents
the coefficient of rolling friction.

FREE BODY DIAGRAM AND NEWTON'S LAW

The system can be represented by following Free Body Diagrams.

From Newton's law, you know that the sum of forces acting on a mass equals the mass times its
acceleration. In this case, the forces acting on M1 are the spring, the friction and the force
applied by the engine. The forces acting on M2 are the spring and the friction. In the vertical
direction, the gravitational force is canceled by the normal force applied by the ground, so that
there will be no acceleration in the vertical direction.
Write down the equations of motion in the horizontal direction:
1. -----------------------------------------------------------------------------2. -----------------------------------------------------------------------------STATE-VARIABLE AND OUTPUT EQUATIONS
10 | P a g e

This set of system equations can now be manipulated into state-variable form. The state variables
are the positions, X1 and X2, and the velocities, V1 and V2; the input is F.
Write down the state variable equations:
1.
2.
3.
4.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

STATE-SPACE

One of the methods to solve the problem is to use the state-space form. Four matrices A, B, C,
and D characterize the system behavior, and will be used to solve the problem.
Find the state-space from the state-variable and the output equations found earlier to match the
following form:[] = ()[] + ()[]

11 | P a g e

TRANSFER FUNCTION

Find the transfer function of the system; you should first take the Laplace transforms of the
differential equations.

12 | P a g e

M ATLAB REPRESENTATION

Now we will see you how to enter the equations you have derived above into an m-file for
MATLAB. Since MATLAB cannot manipulate symbolic variables, let's assign numerical values to
each of the variables as follows:

M1 = 1 kg
M2 = 0.5 kg
k = 1 N/m
F= 1 N
u= 0.002 sec/m ; (mu)friction coefficient
g = 9.8 m/s^2

Now you have to use the state-space form to solve the problem, type help ss to see how to use the
state space function.
Find the transfer function of your system using the ss2tf command. Check the matlab help for
that.

13 | P a g e

SIMULINK BASICS TUTORIAL

Simulink is a graphical extension to MATLAB for modeling and simulation of systems. In


Simulink, systems are drawn on screen as block diagrams. Many elements of block diagrams are
available, such as transfer functions, summing junctions, etc., as well as virtual input and output
devices such as function generators and oscilloscopes. Simulink is integrated with MATLAB and
data can be easily transfered between the programs. In these tutorials, we will apply Simulink to
the examples from the MATLAB tutorials to model the systems, build controllers, and simulate
the systems.
STARTING SIMULINK

Simulink is started from the MATLAB command prompt by entering the following command:
simulink

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

14 | P a g e

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

A new model can be created by selecting New from the File menu in any Simulink window (or
by hitting Ctrl+N).

15 | P a g e

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:


1. Sources: Used to generate various signals
2. Sinks: Used to output or display signals
3. Discrete: Linear, discrete-time system elements (transfer functions, state-space models,
etc.)
4. Linear: Linear, continuous-time system elements and connections (summing junctions,
gains, etc.)
5. Nonlinear: Nonlinear operators (arbitrary functions, saturation, delay, etc.)
6. 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.

16 | P a g e

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.

Lines can never inject a signal into another line; lines must be combined through the use of a
block such as a summing junction.
A signal can be either a scalar signal or a vector signal. For Single-Input, Single-Output systems,
scalar signals are generally used. For Multi-Input, Multi-Output systems, vector signals are often
used, consisting of two or more scalar signals. The lines used to transmit scalar and vector
signals are identical. The type of signal carried by a line is determined by the blocks on either
end of the line.

17 | P a g e

SIMPLE EXAMPLE

The following model 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 transfered 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.

There are many more types of blocks available in Simulink, some of which will be discussed
later. Right now, we will examine just the three we have used in this model.

18 | P a g e

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+4, enter the following into the denominator field:
[1 2 4]

19 | P a g e

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 "step" block can also be double-clicked, bringing up the following dialog box.

20 | P a g e

The default parameters in this dialog box generate a step function occurring at time=1 sec, from
an initial level of zero to a level of 1. (in other words, a unit step at t=1). Each of these
parameters can be changed. Close this dialog before continuing.
The most complicated of these three blocks is the "Scope" block. Double clicking on this brings
up a blank oscilloscope screen.

When a simulation is performed, the signal which feeds into the scope will be displayed in this
window. Detailed operation of the scope will not be covered in this tutorial. The only function
we will use is the autoscale button, which appears as a pair of binoculars in the upper portion of
the window.
RUNNING SIMULATIONS

21 | P a g e

To run a simulation, we will work with the previous 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 or use the play button.

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 autoscale button (binoculars), which will rescale the axes as shown
below.

22 | P a g e

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 autoscale button only changes the vertical axis. Since the new transfer function
has a very fast response, it it 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.

23 | P a g e

There are many simulation parameter options; we will only be concerned with the start and stop
times, which tell Simulink over what time period to perform the simulation. Change Start time
from 0.0 to 0.8 (since the step doesn't occur until t=1.0. Change Stop time from 10.0 to 2.0,
which should be only shortly after the system settles. Close the dialog box and rerun the
simulation. After hitting the autoscale button, the scope window should provide a much better
display of the step response as shown below.

24 | P a g e

CLASSWORK - BUILDING SYSTEMS

In this section, you are required to know how to build systems in Simulink using the building
blocks in Simulink's Library. You should build the following system.

1.
2.
3.
4.
5.

First you will gather all the necessary blocks from the block libraries.
Then you will modify the blocks so they correspond to the blocks in the desired model.
Finally, you will connect the blocks with lines to form the complete system.
After this, you will simulate the complete system to verify that it works.
Show the results to your instructor.

25 | P a g e

EXERCISE 2
SIMULINK MODELING TUTORIAL

In Simulink, it is very straightforward to represent a physical system or a model. In general, a


dynamic system can be constructed from just basic physical laws. We will demonstrate through
an example.
TRAIN SYSTEM

In this example, we will consider a toy train consisting of an engine and a car. Assuming that the
train only travels in one direction, we want to apply control to the train so that it has a smooth
start-up and stop, along with a constant-speed ride.
The mass of the engine and the car will be represented by M1 and M2, respectively. The two are
held together by a spring, which has the stiffness coefficient of k. F represents the force applied
by the engine, and the Greek letter, mu (which will also be represented by the letter u), represents
the coefficient of rolling friction.

FREE BODY DIAGRAM AND NEWTON'S LAW

The system can be represented by following Free Body Diagrams.

From Newton's law, you know that the sum of forces acting on a mass equals the mass times its
acceleration. In this case, the forces acting on M1 are the spring, the friction and the force
applied by the engine. The forces acting on M2 are the spring and the friction. In the vertical
direction, the gravitational force is canceled by the normal force applied by the ground, so that
there will be no acceleration in the vertical direction. You should begin to construct the model
simply from the expressions:
Sum(forces_on_M1)=M1*x1''
Sum(forces_on_M1)=M1*x1''

26 | P a g e

Follow these steps to get your simulink model that represents your system:
1. Derive the set of system equations.
2. Open a new Simulink model window.
3. Figure out the required Simulink blocks and drag them to your model from the Simulink
library.
4. Begin with input to the system; get the appropriate source block and label them.
5. Bring sink block and label it as your output.
6. Complete constructing the equations of motion using the appropriate blocks.
7. Once the model is complete. Save your model.
8. Before running the model, we need to assign numerical values to each of the variables
used in the model. For the train system, let

M1 = 1 kg
M2 = 0.5 kg
k = 1 N/sec
F= 1 N
u = 0.002 sec/m
g = 9.8 m/s^2

Create an new m-file and enter the following commands.


M1=1;
M2=0.5;
k=1;
F=1;
mu=0.002;
g=9.8;

Execute your m-file to define these values. Simulink will recognize MATLAB variab for use in
the model
9. Run the model.

27 | P a g e

OBTAINING M ATLAB MODEL

We can now extract a MATLAB model (state-space or transfer function) from out simulink
model. In order to do this, delete the scope that represent your desired output and put an Out
Block (from the Sinks library) in its place. Also, delete the source block that represents your
input to the system and put an In Block (from the Sources library) in its place. The in and out
blocks define the input and output of the system we would like to extract.
Save this model as Simulink_Tutorial.mdl or download our version here. Now, we can extract
the model into MATLAB. Enter the following command at the MATLAB command window to
extract a state-space model.
[A,B,C,D]=linmod('Simulink_Tutorial')

You should get the state-space model of your Simulink model on the Matlab command window..
To obtain a transfer function model, enter the following command at the MATLAB command
prompt.
[num,den]=ss2tf(A,B,C,D)
These models are equivalent (although the states are in different order) to the model obtained by
hand in the previous lab handout (MATLAB tutorial).

28 | P a g e

Das könnte Ihnen auch gefallen