Matlab Tutorial June15 2005
Matlab Tutorial June15 2005
Jitkomut Songsiri
Lecture 1 Introduction
MATLAB is a computer program that can be very helpful in solving the kinds of mathematical problems you will frequently encounter. MATLAB can solve a wide variety of numerical problems, from the very basic to complex problems. MATLAB can be used to plot several kinds of graphs
Introduction
12
Software Windows Linux Free Software Mathematica http://www.wolfram.com/products/mathematica/index.html SciLab http://scilabsoft.inria.fr/ Octave http://www.octave.org Maple http://www.maplesoft.com
Lecture 2 Variables
Variables
Double array
21
Generate at the command line. >> x = 1 x = 1 >> y = [1 2] y = 1 2 >> z = [1 -1 0; 0 1 -1; 0 0 z = 1 -1 0 0 1 -1 0 0 1 >> whos x y z Name Size Bytes x 1x1 8 double y 1x2 16 double z 3x3 72 double
Matlab tutorial, June 15, 2005
A scalar, a vector , or a matrix is stored as a double array with dierent sizes. A polynomial is also stored as a row vector. 1] q (s) = s2 + 5s + 2 >> q = [1 5 2]
Variables
Char array
22
>> str = hello str = hello >> whos str Name Size Bytes Class str 1x5 10 char array Grand total is 5 elements using 10 bytes
str is stored in a char array whose size is equal to the number of characters
The help command The lookfor command The help desk and link to the mathworks The workspace The save command The search path Disk le manipulation
31
To get syntax and instructions for inv, help inv INV Matrix inverse. INV(X) is the inverse of the square matrix X. A warning message is printed if X is badly scaled or nearly singular. See also SLASH, PINV, COND, CONDEST, LSQNONNEG, LSCOV. All functions are organized into directories, e.g., all linear algebra functions are in matfun. To list the name and description of functions in matfun, help matfun
Matlab tutorial, June 15, 2005
32
Alternatively, to list the name only, what matfun The command help alone lists all the directories, help HELP topics: matlab\general matlab\ops matlab\lang ... - General purpose commands - Operators and special . . . - Programming language . . .
33
The help window Select Help Window under the Help menu (on PCs) Click the question mark on the menu bar (on PCs) Type helpwin
34
Search for functions based on a keyword. Search through the rst line of help text. Return the rst line containing a keyword.
For example, help inverse inverse.m not found One should type lookfor inverse
Matlab tutorial, June 15, 2005
35
Results: INVHILB ACOS ASIN ATAN ERFINV INV PINV ... Inverse Hilbert matrix. Inverse cosine. Inverse sine. Inverse tangent. Inverse error function. Matrix inverse. Pseudoinverse.
Adding the option -all, lookfor -all inverse searches the entire help text (not just the rst line).
Matlab tutorial, June 15, 2005
36
Provide access to helps and references stored in your system. Many documents in HTML format. Access via internet web browser. Select the Help Desk under the Help menu (on PCs). Type helpdesk on the workspace.
The workspace
37
The area of memory. Accessible from the command line. The commands who and whos show the current contents. who a short list whos size and storage information For example, (variables from the Variables Lecture ) >> who Your variables are: A P sysss B Z sysssz C den systf D num systfz K str syszpk
Matlab tutorial, June 15, 2005
syszpkz x y z
38
Results from whos >> whos Name A B C D K P Z den num str sysss sysssz ...
Matlab tutorial, June 15, 2005
Size 2x2 2x1 1x2 1x1 1x1 1x2 1x1 1x3 1x2 1x5 1x1 1x1
Class double array double array double array double array double array double array double array double array double array char array ss object ss object
39
To delete all the existing variables from the workspace, enter the command clear clear To delete specic variables use the commend clear followed by variables clear A B C D
3 10
Save the contents of the workspace as a MAT-le Read the MAT-le with command load
Save all contents to var_data.mat: save var data Save specic contents: save var data systf
sysss
syszpk
Append the data to var_data.mat: save -append var data systf Restore the saved data to workspace: load var data
Matlab tutorial, June 15, 2005
sysss
syszpk
3 11
To view the search path, Type path. Choose Set Path from the File menu (on PCs). Disk le manipulation Generic system commands: dir, type, delete, and cd. MATLAB dir type delete cd MS-DOS dir type del chdir UNIX ls cat rm cd
The format command Suppressing output Long command lines Command line editing
41
specify the displayed numeric format does not aect computation Example. Display x in dierent formats x = [4/3 1.2345e-6] format short 1.3333 0.0000 format short e 1.3333e+000 1.2345e-006 format short g 1.3333 1.2345e-006 format long 1.33333333333333 0.00000123450000
Matlab tutorial, June 15, 2005
42
format long e 1.333333333333333e+000 1.234500000000000e-006 format long g 1.33333333333333 1.2345e-006 format bank 1.33 0.00 format rat 4/3 1/810045 format hex 3ff5555555555555 3eb4b6231abfd271 Note For proper spacing, use Fixedsys or Courier.
Matlab tutorial, June 15, 2005
Suppressing output
43
Matlab automatically displays results. Need no display. End the line with ;. Useful for: Large outputs, Scripts and functions. Multiple expressions in one line. Separate each with ;. a = 1; b = a+1; Force to display results. Use , instead. a = 1, b = a+1, a = 1 b = 2
Matlab tutorial, June 15, 2005
44
Statement does not t in one line. Use three periods, then Enter. s = 1 -1/2 + 1/3 ... -1/4 + 1/5 - 1/6 ... + 1/7 - 1/8 + 1/9 ... - 1/10 + 1/11 - 1/12 s = 0.6532 Note Blank spaces around =, +, and - are optional. Frequently used inside scripts and functions
45
Suppose you mistakenly enter x = (1 + sqt(5))/2 Undefined function or variable sqt The error is due to the misspell of sqrt. Solutions: Press the key to correct; Guide Matlab with a few characters, and press ; Use command history window.
46
Command line editing keys. Ctrl + Ctrl + Ctrl + p Ctrl + n Ctrl + b Ctrl + f Ctrl + r Ctrl + l Recall previous line Recall next line Move back one character Move forward one character Move right one word Move left one word
47
Ctrl + a Move to beginning of line Ctrl + e Move to end of line Ctrl + u Clear line Ctrl + d Delete character at cursor
Backspace Ctrl + h Delete character before cursor Ctrl + k Delete to end of line
Example Usages
51
Example 1 Check the validation of Euler formula ej = cos + j sin by using the command exp sin cos - Exponential - Sine - Cosine
>> theta= pi/3; >> exp(j*theta) ans = 0.5000 + 0.8660i >> cos(theta)+j*sin(theta) ans = 0.5000 + 0.8660i
Matlab tutorial, June 15, 2005
52
Example 2 Find the absolute value of a complex number, z = a + jb |z | = a2 + b2 by using the command abs real imag sqrt Absolute value Complex real part Complex imaginary part Square root
Generating matrices Loading matrices Concatenation Manipulating rows and columns Matrix relating function
Matrix operations
Generating matrices
61
Generate at the command line. A = [1 -1 0; 0 1 -1; 0 0 1] A = 1 -1 0 0 1 -1 0 0 1 The numeric format of the command window is specied by the format command: Several interesting functions, ones(n,m), zeros(n,m), eye(n).
Matlab tutorial, June 15, 2005
Matrix operations
62
Generate via M-le editor. A = [ 1 -1 0 0 1 -1 0 0 1 ] Save as an M-le, say mat_gen.m, and run at the command line, mat gen.m A = 1 -1 0 0 1 -1 0 0 1 The extension .m can be omitted.
Matlab tutorial, June 15, 2005
Matrix operations
Loading matrices
63
The load command Read binary les (MAT les) Read text les Text les must be a rectangular table of numbers, separated by blanks. For example, create outside Matlab : 16 3 2 5 10 11 8 4 7 Save as matrix.txt, and run load matrix.txt
Matlab tutorial, June 15, 2005
Matrix operations
Concatenation
64
B =
Matlab tutorial, June 15, 2005
C =
D =
0 0 1 .
Matrix operations
65
Matrix operations
66
Delete a row.
A(2,:) = [ ] A = 1 -1 0 0 0 1
Matrix operations
67
Basic arithmetic functions: plus(A,B) or A + B, minus(A,B) or A - B, mtimes(A,B) or A*B, A^b. A scalar is applied to any matrix elementwisely. Other linear algebraic functions: det(A), trace(A), A, inv(A).
Matlab tutorial, June 15, 2005
Matrix operations
68
Matrix operations
69
size and length: size of matrices; length of vectors; outputs of size: Suppose B = X = size(B) X = 2 3 1 1 0 . 0 1 1 [Y, Z] = size(B) Y = 2 Z = 3
Y = size(B,2) Y = 3
Plotting Figure windows Add plots to an existing gure Subplots Print graphics
Graphics in Matlab
Plotting
71
Dierent forms of plot. plot(y) y vs indices of elements. plot(x,y) y vs x. For example, to plot sin(x) from 0 to 2 : x = 0:pi/100:2*pi; y = sin(x); plot(x,y) Note The ; is used to suppressed the output.
Matlab tutorial, June 15, 2005
Graphics in Matlab
72
0.8
0.6
0.4
0.2 Sine of x
0.2
0.4
0.6
0.8
3 x (rad)
Graphics in Matlab
73
legend(sin(x),sin(x-.25),sin(x-.5))
Graphics in Matlab
Plotting (cont.)
74
0.8
0.6
0.4
0.2
0.2
0.4
0.6
0.8
Graphics in Matlab
75
Graphics in Matlab
76
Line styles: - solid -- dashed Marker types: + o * x plus sign, o sign, star sign, x sign, s d ^ v square diamond up triangle down triangle p h > < pentagram hexagram right triangle left triangle : dotted -. dash-dot
Note again that you can edit colors, line styles, and markers interactively.
Matlab tutorial, June 15, 2005
Graphics in Matlab
Plotting examples
77
Graphics in Matlab
78
0.8
0.6
0.4
0.2
0.2
0.4
0.6
0.8
Graphics in Matlab
Figure windows
79
For any graphing functions, No gure window. open a new one. One gure window. use the existing one. Many gure windows. chooses the current gure Make gure #n a current gure. figure(n) Open blank gure. figure
Graphics in Matlab
7 10
The command hold prepares to add a new graph to the existing axis. sys = tf(1,[1 2 3]) [y1,t1] = step(sys); plot(t1,y1,--) hold on [y2,t2] = impulse(sys); plot(t2,y2,:) hold off Toggle holding states : sys = tf(1,[1 2 3]) [y1,t1] = step(sys); plot(t1,y1,--) hold Current plot held [y2,t2] = impulse(sys); plot(t2,y2,:) hold Current plot released
Matlab tutorial, June 15, 2005
Graphics in Matlab
7 11
0.4
0.35
0.3
0.25
0.2
0.15
0.1
0.05
0.05
Graphics in Matlab
Subplots
7 12
The subplot command: Display multiple plots in one window. Print multiple plots on one piece of paper. Type subplot(m,n,p): Partition a window into an m n table of subplots. Select the pth subplot. Figure # runs from and from .
Graphics in Matlab
Subplots (cont.)
7 13
t = 0:pi/10:2*pi; [X,Y,Z] = cylinder(4*cos(t)); subplot(2,2,1); mesh(X) subplot(2,2,2); mesh(Y) subplot(2,2,3); mesh(Z) subplot(2,2,4); mesh(X,Y,Z)
5 5
5 40 30 20 0 10 0 20
5 40 30 20 0 10 0 20
0.5
0.5
0 40 20 0 10 0 30 20
0 5 0 5 5 5 0
Graphics in Matlab
7 14
Saving a gure
Select Save from the File menu. The standard format is FIG.
Exporting gure
Lecture 8 M-Files
An M-File is used to Store the set of commands to be executed at once Create your own function
M-Files
Script M-le
81
For example, save the commands from Graphics in Matlab Lecture to a le named plotsine.m
The command >> plotsine gives the same results as we did and all variables are shown in the workspace.
Matlab tutorial, June 15, 2005
M-Files
My function
82
For example, to calculate age from a given birthdate, we develop a function named cal age.m in Matlab editor. % % % % % CAL_AGE(MONTH,YEAR) give the age of a person by assigning month and year of the birthdate. MONTH and YEAR are specified in numeric format and your age will be returned. [yr,mo] = CAL_AGE(7,1978);
function[yr,mo] = cal_age(month,year) today = clock; % get the current date from clock command yr = today(1)-year- (month > today(2)) ; % year difference mo = today(2)-month + 12*(today(2) < month); % month difference fprintf(Your age is %d years %d months,yr,mo) % print the result end
M-Files
My function (cont.)
83
First, type the information of this function and comment it. This message will be displayed when we run help command. >> help cal age CAL_AGE(MONTH,YEAR) give the age of a person by assigning month and year of the birthdate. MONTH and YEAR are specified in numeric format and your age will be returned. [yr,mo] = CAL_AGE(7,1978); Second, dene input arguments and returned values. Terminate the function by using end function[yr,mo] = cal age(month,year) . . end
Matlab tutorial, June 15, 2005
M-Files
My function (cont.)
84
Third, insert your codes and save this le with the extension .m Your function will be executed by using the lename as a command >> [yr,mo] = CAL_AGE(7,1978)
Your age is 26 years 10 months yr = 26 mo = 10 Note: Variables dened in a function are local. They will not be shown in the workspace. The function can be run only if you are in the same path as the le is kept.
Matlab tutorial, June 15, 2005
TF, SS, ZPK object Frequently Used Commands Classical Design Time-domain analysis Frequency-domain analysis Simulink
TF Object
91
A tf object is a continuous-time or a discrete-time transfer function created by tf command. Dene the numerator and denominator of a transfer function. >> num = [1 2]; den = [1 2 1] ; num and den which are stored as double arrays represent the coecients of the numerator and denominator, respectively. Create a continuous-time transfer function. Create a discrete-time transfer function and specify the sampling time (1 sec). >> systf = tf(num,den) Transfer function: s + 2 ------------s^2 + 2 s + 1 >> systfz = tf(num,den,1) Transfer function: z + 2 ------------z^2 + 2 z + 1 Sampling time: 1
Matlab tutorial, June 15, 2005
SS Object
92
An SS Object is a continuous-time or a discrete-time state-space model. Dene state-space system matrices. >> A = [-0.5 0; 0 -0.2] ; B = [1; 0] ; C =[1 0 ] ; D = 0 ; Create a continuous-time state-space model. >> sysss = ss(A,B,C,D) a = x1 x2 x1 -0.5 0 x2 0 -0.2 c = y1 x1 1 x2 0 b = x1 x2 d = y1 u1 0 u1 1 0
Continuous-time model.
Matlab tutorial, June 15, 2005
SS Object (cont.)
93
Create a discrete-time state-space model and specify the sampling time (1 sec). >> sysssz = ss(A,B,C,D,1) a = x1 x2 x1 -0.5 0 x2 0 -0.2 c = y1 x1 1 x2 0 b = x1 x2 d = y1 u1 0 u1 1 0
ZPK Object
94
Dene zeros (Z), poles (P), and gain (K) of a transfer function. >> Z = -0.5 ; P = [-0.7 -1] ; K = 1 ;
Create a continuous-time ZPK model. >> syszpk = zpk(Z,P,K) Zero/pole/gain: (s+0.5) ------------(s+0.7) (s+1)
Create a discrete-time ZPK model with the sampling time = 1 sec. >> syszpkz = zpk(Z,P,K,1) Zero/pole/gain: (z+0.5) ------------(z+0.7) (z+1) Sampling time: 1
95
Three combinations of conversions among TF, SS, ZPK. Conversion between continuous and discrete models. System poles, zeros, and eigenvalues.
96
TF : Transfer Function SS : State Space Model ZPK : Zeros, Poles, and Gain
ss2zp tf2ss
(s + 1) to the state-space model. 2 (s + 4s + 5) >> num = [1 1]; den = [1 4 5]; >> [a,b,c,d] = tf2ss(num,den) a = b = -4 -5 1 1 0 0 c = d = 1 1 0
Matlab tutorial, June 15, 2005
97
c2d : Conversion of continuous-time models to discrete time. d2c : Conversion of discrete-time models to continuous time.
s+1) For example, convert G(s) = (s2(+4 to a discrete model by assuming Zero-Order hold on s+5) the inputs with the sampling time = 0.1 sec.
>> sysd = c2d(systf,0.1,zoh) Transfer function: 0.08611 z - 0.07791 ---------------------z^2 - 1.629 z + 0.6703 Sampling time: 0.1 Convert to the discrete-time model.
98
According to systf created in the previous slide, we calculate poles, zeros and eigenvalues of the system by the following command. >> pole(systf) ans = -2.0000 + 1.0000i -2.0000 - 1.0000i >> zero(systf) ans = -1 >> eig(systf) ans = -2.0000 + 1.0000i -2.0000 - 1.0000i
The input arguments of pole and zero are LTI models (SS or TF object) The input argument of eig could be: 1. An LTI model (SS or TF object) 2. A square matrix
Classical Design
99
rlocus computes and plots the root locus of a single-input, single-output LTI model sisotool A Graphical User Interface that allows you to design single-input/single-output (SISO) compensators.
Root Locus 2
1.5
0.5
1.5
2 10
4 Real Axis
rlocus
Matlab tutorial, June 15, 2005
sisotool
Root Loci
9 10
In plotting root loci with MATLAB, we deal with the system equation in the form of 1 + KG(s) = 0 For example, let G(s) = (s + 1) . 2 (s + 4s + 5)
num=[1 1];den = [1 4 5]; [a,b,c,d]=tf2ss(num,den); systf = tf(num,den); sysss=ss(a,b,c,d); rlocus(num,den) rlocus(systf) rlocus(a,b,c,d) rlocus(sysss)
9 11
1.5
0.5
0.5
Imaginary Axis
Imaginary Axis
System: systf2 Gain: 1.66 Pole: 3.99 Damping: 1 Overshoot (%): 0 Frequency (rad/sec): 3.99
0.5
0.5
1.5 4.5
3.5
1.5
0.5
1.5 4.5
3.5
1.5
0.5
Clicking at a point on root locus returns the closed-loop poles, feedback gain (K ), and other parameters. The user is able to design the gain (K ) by dragging mouse to the appropriate point corresponding to the desired closed-loop pole and time response specication.
Matlab tutorial, June 15, 2005
SISOTOOL
9 12
This GUI lets you design single-input/single-output (SISO) compensators by interacting with the root locus, Bode, and Nichols plots of the open-loop system.
1. Current parameters of the Compensator 2. Conguration of Feedback System 3. Root Locus 4. Open-Loop Bode Plot
SISOTOOL (cont.)
9 13
Step response, Closed-Loop Bode plot, and other loop responses are provided in analysis menu.
Time-domain analysis
9 14
step Step response impulse Impulse response initial Response of state-space system with given initial conditions.
Step response
9 15
0.3
0.25
0.5
1.5
3.5
4.5
>> step(systf,5)
Matlab tutorial, June 15, 2005
Impulse response
9 16
0.8
0.5
1.5
3.5
4.5
>> impulse(systf,5)
Matlab tutorial, June 15, 2005
Initial response
9 17
The inital response of G(s) from t = 0 to t = 5 with a given initial condition (x0 = [1 1]) can be obtained by:
Response to Initial Conditions 1
0.8
0.6
0.4
Amplitude
0.2
0.2
0.4
0.6
0.8
0.5
1.5
3.5
4.5
>> inital(sysss,[-1 1],5) Note: The rst argument of command initial must be an SS object or state-space model.
Matlab tutorial, June 15, 2005
Frequency-domain analysis
9 18
bode Bode diagrams of the frequency response nyquist Nyquist plot freqresp Frequency response over a frequency grid ltiview Response analysis GUI (LTI Viewer)
Bode
9 19
>> bode(systf) The following command return the response magnitudes and phases in degrees along with the frequency data. >> [MAG,PHASE,W] = bode(systf); >> MAG MAG(:,:,1) = 0.2008
15
20
25
30
35
40 45
45
90 10
1
10
10 Frequency (rad/sec)
10
Nyquist
9 20
The command nyquist draws the Nyquist plot of G(s). >> nyquist(systf)
Nyquist Diagram 1 0.8
0.6
0.4
0.2
0.4
0.6
0.8
1 1
0.8
0.6
0.2
0.2
0.4
Frequency Response
9 21
The frequency response of G(s) (jw + 1) s+1 s=jw G(jw) = G (s ) = 2 s + 4s + 5 (w2 + 4jw + 5) can be computed by : 1. Specifying a vector of frequency grid >> w = logspace(-2,3,500) 0.0100 0.0102 ... 2. Generating the command >> Gjw = freqresp(systf,w) Gjw(:,:,1) = 0.2000 + 0.0004i Gjw(:,:,2) = 0.2000 + 0.0004i ...
Matlab tutorial, June 15, 2005
The commands mag(Gjw) and phase(Gjw) give the same results as that obtained from bode command.
9 22
The LTI Viewer is an interactive graphical user interface (GUI) for analyzing the time and frequency responses of linear systems and comparing many systems in the same time. A blank viewer is run by >> ltiview
9 23
9 24
2. Select the option of graphs to be displayed. For example, step and bode response will be shown in the same window.
Simulink
9 25
Simulink is a tool for creating a diagram of a particular system and simulating its time response. See an example in the class.
References
9 26
[1] Matlab Help [Computer Software], The Mathworks Inc., version 6.5.0.180913a, Release 13, 2002. [2] W. Khaisongkram, MATLAB Tutorial, CSRL, Dept. of Electrical Engineering, Chulalongkorn University, July 2004.