Matlab Tutorial
Matlab Tutorial
22/09/2014
Email: [email protected]
Contents
1 What is MATLAB? 2
4 Data structures 3
4.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.2 Vectors and Arrays . . . . . . . . . . . . . . . . . . . . . . . . 4
4.3 Character string . . . . . . . . . . . . . . . . . . . . . . . . . 5
4.4 Matrix arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
4.5 Element-by-element matrix operations . . . . . . . . . . . . . 5
4.6 Cell arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.7 Complex numbers . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.8 Checking existing variables . . . . . . . . . . . . . . . . . . . 6
5 Functions 7
5.1 Built-in functions . . . . . . . . . . . . . . . . . . . . . . . . . 7
5.2 User-defined functions . . . . . . . . . . . . . . . . . . . . . . 7
6 Graphs 8
6.1 Basic plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
6.2 Multiple plot . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1
8 Control system toolbox 10
8.1 Transfer function . . . . . . . . . . . . . . . . . . . . . . . . . 10
8.2 Control systems and their design . . . . . . . . . . . . . . . . 11
9 Simulink 13
9.1 Block diagramm . . . . . . . . . . . . . . . . . . . . . . . . . 13
9.2 Example: simulating the motion of a pendulum . . . . . . . . 14
10 Conclusion 18
1 What is MATLAB?
The meaning of the word MATLAB is Matrix Laboratory, as it sup-
ports array (matrix) type data structures. MATLAB is a high-level language
and interactive environment for numerical computation, visualization, and
programming. Using MATLAB, you can analyze data, develop algorithms,
create models and applications. In this way it is suitable to write user defined
functions using the the built-in functions for solving complex mathematical
problems such us numerical simulations of ordinary differential equations or
operations with big data and so on. The aim of this tutorial to introduce
the basic concept and application possibilities of this program via various
examples.
– Command Window
We can write here commands (in the command line), define variables,
or call any of the existing functions
– Editor
We can write here a whole script or create our own functions using
various built-in functions and save it in a ’.m’ file.
2
Figure 1: Command Window
– Current Folder
Inform us about the content of the folder where we are working in.
Before we start writing the script, we need to make sure we are in the
right folder to save the files. Best way is to create a working folder
we start to work, set this folder as Current Folder, so we save here
everything immediately.
– Command History
Stores all commands we typed in the Command Window. We recall the
these commands by pressing the ’up’ button on the keyboard while the
cursor is in the command line.
4 Data structures
MATLAB supports array structures, it stores the elements automatically
in double precision floating points (double), however the user can define other
data types:
help datatypes
3
Figure 2: Editor
4.1 Variables
We can define the variables as follows:
a=.132456;
b=1e5;
b
b=
100000
When we type without ’;’, MATLAB lists the variable name and its value in
Command Window.
4
4.3 Character string
We can store characters in variables:
S= ’I am a student in CUHK’
S=
I am a student in CUHK
S(4)
lists the 4th character, which is m in our case.
• Subtraction −
5
• Multiplication .*
• Division ./
• Exponentiation .∧
C1={a}
C1 =
[0.1325]
C2=cell(1,3)
C2{1}=S
C2 =
[1x22 char] [] []
c1=1+2i;
c2=(1+2i)*(3+4j)
c2 =
-5.0000 +10.0000i
6
The last one lists also the properties of the used variables.
clear all
clears all the variables which are in use.
clc
clears the command window.
5 Functions
Arithmetic expressions often require computations other than addition,
subtraction, multiplication, division, and exponentiation, e.g., many expres-
sions require the use of logarithms, exponentials, and trigonometric func-
tions.
7
function [root1,root2]=quad(a,b,c)
D = b2 -4*a*c;
root1 = (-b+sqrt(D))/2/a;
root2 = (-b-sqrt(D))/2/a;
where a,b,c are coefficients of the quadratic function, root1 and root2 are the
solutions of the function. ’sqrt’ calculates the square root.
Let us solve the following qudratic function:
x2 + 3x + 2 = 0 (2)
Type to the Command Window:
Our function ’quad’ gives us the solution of (2). The roots are -1 and -2.
6 Graphs
We can plot nice figures in MATLAB. We use the ’plot’ function to create
the plot. In this section we deal with 2D plotting, but MATLAB can plot
3D figures, too.
figure(1)
x=linspace(-4,1,50);
y=a* x .2 +b*x+c;
If there is a ’.’ before the sign of the operation, it means the operation is
going to be executed element-by-element.
plot(x,y)
We call the ’plot’ function. The elements of x concern the horizontal axis,
the elements of y concern the vertical axis.
8
6.2 Multiple plot
xlabel(’x’)
ylabel(’y’)
title(’Multiple plot’)
Let us give the label ’x’ for the horisontal, and ’y’ for the vertical one, and let
us give the name ’Multiple plot’ for the whole figure utilizing ’title’ command.
grid on
We turn the grid lines on in the figure.
hold on
We keep the figure window switched on to plot there more functions in the
following way:
plot(x,sin(x),’mx-’,x,cos(x),’co-’)
We call the functions ’sin’ and ’cos’ to calculate sine and cosine of x in every
point. We can define different line colors, different markers and different line
types as well. For further information, please browse Help menu for Line
Properties.
hold off
We finished plotting in the figure window.
The three figures can be seen now in one figure, see Figure 3.
Multiple plot
6
3
y
−1
−4 −3 −2 −1 0 1
x
9
7 Help and supporting toolboxes
MATLAB has a so called in-screen help system. If we type
help
help control
help tf
s2 + 2s + 3 (3)
s+1 (4)
A1=[1, 2, 3];
B1=[1, 1];
Let us name A1 and B1 the two vectors of coefficients ot the two polynomi-
als.
C1=conv(A1,B1);
printsys(B1,C1)
num/den =
s+1
———————
s3 + 3 s2 + 5 s + 3
We can easily expand the polynomial by taking convolution between the vec-
tors representing the 2 polynomial (3) and (4) factors, using the command
’conv’. The other command, ’printsys’ prints the system with numerator B1
10
and denumerator C1.
We can create directly transfer functions with the ’tf’ function:
num=1;
den=[1 1 1];
sys=tf(num,den);
[r,p,k]=residue(num,den)
r=
0 - 0.5774i
0 + 0.5774i
p=
-0.5000 + 0.8660i
-0.5000 - 0.8660i
k=
[]
The ’residue’ function calculates the residues ’r’, the poles ’p’ and the direct
term ’k’.
From the transfer function we can formulate the State Space (SS) model (5):
11
1
0.8
0.6
y(t)
0.4
0.2
0
0 2 4 6 8 10
t
Finally, let us print the Bode (’bode’) diagram, see Figure 5, and the
Nyquist (’nyquist’) diagram, see Figure 6, and calculate the gain (’Gm’) and
phase (’Pm’) margin and the corresponding frequencies. For this purpose, we
use the ’margin’ function:
figure(3)
bode(sys)
grid on
figure(4)
nyquist(sys)
grid on
[Gm,Pm,Wcg,Wcp] = margin(sys)
Gm =
Inf
Pm =
90
Wcg =
Inf
Wcp =
1.0000
12
Bode Diagram
20
0
Magnitude (dB)
−20
−40
−60
−80
0
−45
Phase (deg)
−90
−135
−180
−2 −1 0 1 2
10 10 10 10 10
Frequency (rad/s)
The term ’Inf’ means that the value is infinite. That is because the phase
curve never will reach the value -180 degree. See Figure 5. Sometimes the
resulting value is ’NaN’, which means the calculated value is Not a Number.
9 Simulink
Simulink is an extension to MATLAB that allows engineers to rapidly
and accurately build computer models of dynamic physical systems using
block diagram notation. We may simulate linear and nonlinear systems,
continuous-time and discrete-time components furthermore graphical ani-
mations are possible to create.
13
Nyquist Diagram
1.5
2 dB 0 dB −2 dB
−4 dB
1
4 dB
−6 dB
6 dB
0.5
10 dB −10 dB
Imaginary Axis
20 dB −20 dB
0
−0.5
−1
−1.5
−1 −0.5 0 0.5 1 1.5
Real Axis
14
according to [1]. The scheme of the model is as follows (Figure 7):
d2 φ
mR2 + mgR sin φ = 0
dt2
Let us recall the dynamics of a simple pendulum with length R and mass m.
The equation of mottion is as follows:
d2 φ dφ
mR2 +η + mgR sin φ = 0 (6)
dt2 dt
If a torque N is applied on a stacionary pendulum it will swing out
through the angle φ. The damping force Fdamp = ηω. To overwrite the dif-
ferential equation above, we add the damping torques. Where η is a damping
ratio.
Data:
m = 0.07 kg,
R = 0.3 m,
η = 0.003.
1. Launch Simulink. See Figure 1 and click on Simunlink Library icon
on the middle-top.
15
Figure 9: New Simulink model
16
Figure 11: Block diagram of the pendulum
4. Double check if every block is set. Make sure that the initial
condition of the 2 integrator is set, like in Figure 12:
17
Functions). Double click on the block and enter in pndanim1 in the
S-Function Name box. Also enter in ts for the S-Function parameter
(ts, or the sampling time, is the argument taken by the pndanim1
function) and hit OK. Highlight the S-Function block and create a
subsystem (Ctrl + G). Double-click on the subsystem and delete the
Out1 block since we will not need it. Then right click and Add Mask.
Add ts parameter: Double-click on the subsystem block and enter in a
10 Conclusion
This is a very brief introduction to MATLAB. You may be interested in
learning more, please check http://www.mathworks.com/academia/students.
html?s_tid=acmain_sp_gw_bod, http://ctms.engin.umich.edu/CTMS/index.
php?aux=Home and https://www.facebook.com/MATLAB
18
Figure 14: Configuration of parameters
References
[1] Herbert Goldstein. Classical mechanics, volume 4. Pearson Education
India, 1962.
19