Professional Documents
Culture Documents
MATLAB Tutorial: Qian Wang Mechanical Engineering Penn State University
MATLAB Tutorial: Qian Wang Mechanical Engineering Penn State University
Qian Wang
Mechanical Engineering
Penn State University
MATLAB Fundamentals
Plotting Figures
M-files
ODE Solver
Building Control Systems
Time Response
Root Locus
Frequency Response / Bode Plot
SIMULINK
1
Getting Started
Starting MATLAB
Click the MATLAB icon on Windows to start MATLAB command window, which gives
an interactive interface. The top menu bar can be used to open or write a M-file, which
will be addressed later. Once started, MATLAB will provide some introductory remarks
and pop up the MATLAB prompt >>.
Help Facility
By typing “help”, “help <topics>”, you can get on-line help.
» help
HELP topics:
» help ode23
2
which saves the current variable “x, y” into “temp.mat”.
To retrieve all the variables from the file named “temp.mat”, type
» load temp
Exit
Exit MATLAB by typing
» quit
or
» exit
Fundamental Expressions/Operations
MATLAB uses conventional decimal notion, builds expressions with the usual arithmetic
operators and precedence rules:
» x = 3.421
x=
3.4210
» y = x+8.2i
y=
3.4210 + 8.2000i
» z = sqrt(y)
z=
2.4805 + 1.6529i
» p = sin(pi/2)
p=
Matrix Operations
Matrix operations are fundamental to MATLAB. Within a matrix, columns are separated
by space, and the rows are separated by semicolon”;”. For example
3
» A = [1 2 3; 4 5 6; 7 8 9]
A=
1 2 3
4 5 6
7 8 9
» B = ones(3,3)
B=
1 1 1
1 1 1
1 1 1
» A+B
ans =
2 3 4
5 6 7
8 9 10
» A'
ans =
1 4 7
2 5 8
3 6 9
+ addition
- subtraction
* matrix multiplication
^ power
‘ transpose
\ left division
/ right division
Building Matrix
Convenient matrix building functions are
4
eye identity matrix
zeros matrix of zeros
ones matrix of ones
diag diagonal matrix
triu upper triangular part of a matrix
tril lower triangular part of a matrix
rand randomly generated matrix
For example,
» A = eye(3)
A=
1 0 0
0 1 0
0 0 1
» B = zeros(3,2)
B=
0 0
0 0
0 0
» C = rand(3,1)
C=
0.9501
0.2311
0.6068
» D = [A B C D]
D=
1.0000 0 0 0 0 0.9501
0 1.0000 0 0 0 0.2311
0 0 1.0000 0 0 0.6068
5
» D(:,6)
ans =
0.9501
0.2311
0.6068
» D(1, :)
ans =
1.0000 0 0 0 0 0.9501
» D(1,6)
ans =
0.9501
E=
Vector Functions
Certain functions in MATLAB are “vector functions”, i.e., they operate essentially on a
vector (row or column). For example, the maximum entry in a matrix D is given by
max(max(D)).
» max(D)
ans =
» max(max(D))
ans =
A few of these functions are: max, min, sort, sum, prod, mean, std, any, all.
6
Matrix functions
The most useful matrix functions are
For example
» F = rand(3,3)
F=
» eig(F)
ans =
1.7651
0.0310
-0.4997
» rank(F)
ans =
» cond(F)
ans =
69.1503
» inv(F)
ans =
7
17.9446 -0.1385 -9.9689
8.6579 -1.6802 -3.5560
-26.2485 1.8760 14.5444
Plotting Figures
Creating a Figure
If y is a vector, “plot (y)” produces a linear graph of the elements of y versus the index of
the elements of y. If you specify two vectors as arguments, “plot(x,y)” produces a graph
of y versus x.
» t = 0:pi/100:2*pi;
» x = sin(t);
» y1 = sin(t+0.25);
» y2 = cos(t-0.25);
» figure(1) % open a figure and make it current, not necessarily
» plot(x,y1,'r-',x,y2, 'g--')
» title('sin-cos plots')
» xlabel('x=sin(t)')
» ylabel('y')
sin-cos plots
1
0.5
0
y
-0.5
-1
-1 -0.5 0 0.5 1
x=sin(t)
By plotting multiple figures on the graph, one alternative way is to use “hold on”
and “hold off” commands,
» plot(x,y1, 'r-')
» hold on
8
» plot(x,y2, 'g--')
» hold off
y yellow . point
m magenta o circle
c cyan x x-mark
r red + plus
g green * star
b blue - solid
w white : dotted
k black -. dashdot
-- dashed
Exporting a Figure
1) Cut and paste: click “Edit” at the top menu bar of the figure window, then click
“Copy Figure”, paste the figure wherever you want.
2) Save as a file: print –tiff –deps (print as a postscript file). Type “help print” to
find out more options.
M-files
MATLAB can execute a sequence of statements in a file. Such files are called “M-files”
because they must have the file type of “.m” as the last part of their filename. There are
two types of M-files: script files and function files.
Script files
A script file consists of a sequence of normal MATLAB statements. For example, type all
the commands for generating the figure into a single script file and save as “sineplot.m”.
Then the MATLAB command “sineplot” will cause the statements in the file to be
executed. Try it.
Function files
9
You can create new functions specific to your problem, which will then have the same
status as other MATLAB functions. Variables in a function files are by default local,
otherwise need to be declared as “global”. The function file will start with
a=
q=
0.2929
10
First transform a high-order differential equation into a set of first-order differential
equations. Then create a function M-file containing these differential equations. For
example,
x&1 = x1 (1 − x 22 ) − x 2
x& 2 = x1
To simulate the differential equation defined in “vdpol” over the interval [0,20], invoke
ode23
t0 = 0; tf = 20;
x0 = [0 0.25]’; % Initial conditions
[t,x] = ode23(‘vdpol’, [t0 tf], x0);
plot (t, x)
-1
-2
-3
0 2 4 6 8 10 12 14 16 18 20
11
Setting Up Control Systems
5( s + 5.3)
G ( s) =
( s + 2.1)( s + 15)
Transfer function:
5 s + 26.5
-------------------
s^2 + 17.1 s + 31.5
For SISO models, “num” and “den” are row vectors listing the numerator and
denominator coefficients in descending powers of s by default.
a=
x1 x2 x3
x1 -23.5 -13.1 -4.5
x2 1.8 0 0
x3 0 1 0
b=
u1
x1 1
x2 0
x3 0
12
c=
x1 x2 x3
y1 0 18 23
d=
u1
y1 0
a=
x1 x2
x1 -17.1 -3.9375
x2 8 0
b=
u1
x1 4
x2 0
c=
x1 x2
y1 1.25 0.82813
d=
u1
y1 0
Transfer function:
32.4 s + 41.4
------------------------------
s^3 + 23.5 s^2 + 23.58 s + 8.1
13
Other commands on building models and extract data from a model
zpk - Create a zero/pole/gain model.
ssdata - Extract state-space matrices.
zpkdata - Extract zero/pole/gain data.
tfdata - Extract numerator(s) and denominator(s).
For example, we would like to compute and plot step response for a system with no
zeros, poles at s= -1+3i and s = -1-3i, and a gain of 3.
Zero/pole/gain:
3
---------------
(s^2 + 2s + 10)
» step (sys_3)
Step Response
0.4
0.35
0.3
0.25
Amplitude
0.2
0.15
0.1
0.05
0
0 1 2 3 4 5 6
Time (sec.)
14
Root Locus Plots
For example, draw root locus plot for a transfer function model
s+2
G(s) =
2
s + 4s + 9
2.5
1.5
0.5
Imag Axis
-0.5
-1
-1.5
-2
-2.5
-6 -5 -4 -3 -2 -1 0 1 2
Real Axis
Bode Plot
» num =[1 2];
» den = [1 4 9];
» bode(num, den)
15
Bode Diagrams
-10
-20
-20
-40
-60
-1 0 1
10 10 10
Frequency (rad/sec)
SIMULINK
SIMULINK is a program for simulating dynamic systems. It has two phases of use:
model definition and model analysis. Model definition uses the metaphor of a block
diagram, which is much like drawing a block diagram. Instead of drawing the individual
blocks, blocks are copied from libraries of blocks. After you define a model, you can
analyze it either by choosing options from the SIMULINK menus or by entering
commands in MATLAB’s command window. The progress of a simulation can be
viewed while the simulation is running, and the final results can be made available in the
MATLAB workspace when a simulation is complete.
This command displays a new window containing icons for the subsystem blocks
In1 Out1
Select “New” from the “File” menu on its menu bar to open a new empty window labeled
“Untitled”, you can rename it when you save it. The new window is where you construct
your system model by dragging blocks from their original location to the new window.
Notice that when you drag a block to a different window you drag only a copy of the
block.
16
Example: Building a simple SIMULINK model for a spring-mass-damper system with
nonlinear friction.
The spring-mass-damper system is taken from the text book, “Dynamic modeling and
control of engineering systems”, Figure 6.6 on Pg. 137.
Stiffness
1 1
1
s s
Step Sum 1/m Velocity Displacement Monitor
ouput
Coulomb &
Viscous Friction
17
• Double click “Stiffness”, set the gain value as 1.0.
• Double click “1/m” block, set the gain value as 1.0.
• Double click “Coulomb friction”, set offset as 0.5 and gain as 1.8.
• Double click “Monitor output”, click the “properties” button next to the
“print” button, set Ymax as 2.5, and Ymin as –0.5.
• Go back to the model window, select “Parameters” from the “Simulation”
menu. Set simulation time: start time = 0.0, and stop time = 5.0
18
References
19