Upload
leightamika
View
223
Download
0
Embed Size (px)
Citation preview
7/31/2019 1) Matlab_Miniguide
1/22
Chemical Engineering Department
University of Florida
Oscar D. Crisalle 1997-2009 File Name: Matlab_Miniguide_Rev_7.3.doc
MATLAB MINIGUIDEby Prof. Oscar D. Crisalle
CONTENTS
1.1 MATLAB Manuals and Literature ..............................................................................................11.1.1 Manuals and Tutorials Available at CIRCA ..................................... 1
1.2 Introduction to MATLAB .............................................................................21.2.1 Modes of Using MATLAB ..............................................................21.2.2 Executing the MATLAB Program....................................................21.2.3 Exiting from the MATLAB Program ............................................... 21.2.4 Obtaining On-Line Help .................................................................. 21.2.5 Useful Keyboard Commands ...........................................................31.2.6 Adjusting the Format of Numbers Displayed....................................3
1.3 List of Essential Commands and Operators .................................................41.4 Overview of MATLAB Operations ...............................................................5
1.4.1 Defining Vectors, Matrices and Polynomials....................................51.4.2 Defining Three Useful Functions ones, zeros, eye ........................ 61.4.3 Defining Transcendental Functions sin, cos, log, exp ...................71.4.4 Defining Basic Operations det, eig, conv, poly.............................8
1.5 Advanced MATLAB Commands ..................................................................101.5.1 Plotting............................................................................................101.5.2 Displaying to the Screen .................................................................. 111.5.3 Operating with Strings of Characters................................................121.5.4 Appending Results to a Vector or a Matrix.......................................131.5.5 Taking Input from the Keyboard ......................................................141.5.6 Creating a Diary File........................................................................ 151.5.7. Creating an M-File.......................................................................... 151.5.8
If Structure.......................................................................................16
1.5.9 While Structure................................................................................161.5.10 For Structure..................................................................................171.5.11 Break Command ............................................................................171.5.12 M-Functions...................................................................................181.5.13 Quadrature/Numerical Integration.................................................. 201.5.14 ODE23/ODE45..............................................................................21
7/31/2019 1) Matlab_Miniguide
2/22
Oscar D. Crisalle 1997-2009 - 1 - MATLAB Miniguide
1.1 MATLAB MANUALS AND LITERATURE
Program name:
MATLAB (personal computers)
PRO-MATLAB (workstations)
Note: Manuals may be titledMATLAB or PRO-MATLAB.
Basic manuals an documentation:
a. MATLAB user's guide (tutorial and reference)
b. Control Toolbox manual
c. SIMULINK Manual
d. Various manuals for each toolbox
1.1.1 Manuals and Tutorials Available at CIRCA
a. CIRCA Lab:
Room: CSE 211 - Phone: 392-2446
Hours: M-F 8:00 AM - midnight Sat. Noon - Midnight
b. CIRCA consultants office
Room: CSE 520 - Phone: 2-HELP (2-4357)
Hours: M-F 9:00 AM - 5:00 PM
7/31/2019 1) Matlab_Miniguide
3/22
Oscar D. Crisalle 1997-2009 - 2 - MATLAB Miniguide
1.2 INTRODUCTION TO MATLAB
MATLAB is a high-level computer language with powerful commands that emphasize
numerical operations with matrices. The word MATLAB itself is derived from the words
MATrix LABoratory. Originally MATLAB carried out only linear algebra calculations (matrix
operations) but has now been extended to include operations useful for signal processing, control
analysis and design, nonlinear differential equations, and many others. These extensions are
done by a number of routines collected under directories called Toolboxes, such as the following:
Control toolbox Robust control toolbox
Identification toolbox MFD (multivariable frequency design) toolbox
Optimization toolbox Splines toolbox
The related program SIMULINK includes MATLAB plus additional capabilities for
simulating nonlinear dynamic systems. MATLAB is available in almost all computer platforms
(IBM, Macintosh, HP, Sun, DEC). All commands remain unchanged from one computer to
another.
1.2.1 Modes of Using MATLAB
a. Interactive (commands issued using a keyboard).
b. M-files (programs) , which can be of three types: (1) M-scripts (also called M-files),
(2) M-functions, and (3) SIMULINK M-files.
1.2.2 Executing the MATLAB Program
Type: matlab
The prompt >> appears, indicating that MATLAB is ready to receive interactive
commands.
1.2.3 Exiting from the MATLAB Program
Type: >> quit
Note that you only need to type the word quit; the symbol >> is the MATLAB prompt.
1.2.4 Obtaining On-Line Help
Type: >> help to get a list of commands
7/31/2019 1) Matlab_Miniguide
4/22
Oscar D. Crisalle 1997-2009 - 3 - MATLAB Miniguide
Example: to get help on the command dir type: >> help dir
Type: >> demo to get a demonstration of some of MATLAB's features.
1.2.5 Useful Keyboard Commands
Repeats previous command
Advances to next command
Move left on command line
Move right on command line
^a Move to beginning of command line
^e Move to end of command line
^d Delete next character
Backspace Delete previous character
1.2.6 Adjusting the Format of Numbers Displayed
format short shows 5 digits
format short e shows 5 digits in exponential form
format long shows 15 digits
format long e shows 15 digits in exponential form
format compact does not display extra blank line after each answer is
echoed
7/31/2019 1) Matlab_Miniguide
5/22
Oscar D. Crisalle 1997-2009 - 4 - MATLAB Miniguide
1.3 LIST OF ESSENTIAL COMMANDS AND OPERATORS
The following commands must be thoroughly studied from the MATLAB manual (or
tutorial) so you may carry out the essential operations available.
diary
save, load
help
who, whos, size, dir, clear
inv
eig
zeros, ones, eye
conv
roots
format short, format compact, format short e
plot, hold, axis, title, text, shg, clg, semilog, loglog, subplot
%
' (apostrophe)
: (colon)
; (semicolon)
, (comma)
All of these commands must be typed in lowercase (MATLAB is case-sensitive).
To learn more about a command, type help. Example: >> help whos
7/31/2019 1) Matlab_Miniguide
6/22
Oscar D. Crisalle 1997-2009 - 5 - MATLAB Miniguide
1.4 OVERVIEW OF MATLAB OPERATIONS
1.4.1 Defining Vectors, Matrices and Polynomials
>> x = [ 123]
x =
123
Defines column vectorx =
1
2
3
!
"
###
$
%
&&&
Echo displayed on the screen
>> x = [1; 2; 3]
x =1
23
Defines column vectorx =
1
2
3
!
"
###
$
%
&&&
The semicolon indicates that the next element ison a new row (the semicolon is an end-of-row
marker)
>>x = [1 2 3]
x =
1 2 3
Defines row vector x = [1 2 3]
Echo printed on screen
>> x = [1, 2, 3]
x =
1 2 3
Defines row vector x = [1 2 3 ]
The comma indicates that the next element is on
a new column ( the comma is an end-of-columnmarker)
>> A = [5 67 8]
A =5 6
7 8
Defines matrix A
>> A = [5, 6; 7, 8]
A =
5 67 8
Defines matrix A
The comma separates elements on the same row,
and the semicolon separates elements ondifferent rows
>> b = A(2, 2)b =
8
Denotes the element (2, 2) of matrix A
>> b = A(2, :)
b =7 8
Denotes row 2 ofA and all columns of matrix A
>> b = A(:, 2)
b =6
8
Denotes all rows ofA and column 2 of matrix A
7/31/2019 1) Matlab_Miniguide
7/22
Oscar D. Crisalle 1997-2009 - 6 - MATLAB Miniguide
>> b = A(1, 1) + A(2, 2)
b =
13
Sum of elements (1, 1) and (2, 2) of matrix A
>> A(1, 1) + A(2, 2)
ans =
13
Sum of elements (1, 1) and (2, 2) of matrix A
The result is written to the default variable ans>> p = [1 0.9 0.3]
p =1 0.9 0.3
Denotes the polynomial
p(s) = s2 + 0.9s + 0.3
Polynomials are represented as row vectors.>> size(A)
ans =2 2
Finds the number of rows and columns
of matrix A
>> poly2sym([1 0.9 0.3], s)
ans =
s2
+ 0.9s + 0.3
Transforms a row-vector polynomial
representation into a standard symbolic
representation shown the powers of the variable s
and all the terms in the polynomial (requires thatthe Symbolic Toolbox be installed)
>> size(p)
ans =
1 3
Finds the number of rows and columns
of vector p
>> who
Your variables are:A ans b p x
List all variables currently defined
1.4.2 Defining Three Useful Functions ones, zeros, eye
>> B = ones(2, 2)
B =1 1
1 1
Create a matrix consisting of 2 rows and 2columns, and whose entries are all equal to 1
>>B = ones(2, 1)
B =
11
Create a matrix consisting of 2 rows and 1column, and whose entries are all equal to 1
>> A = [5 6 9; 7 8 10], ...
B = ones(size(A))
A =5 6 9
7 8 10B =
1 1 1
1 1 1
More than one command can be given on a line,by separating each individual command with acomma. Commands can also be embedded into
other commands.
The ellipsis (...) indicates that the command
continues on the next line
>> B = ones(3) When only one number is given, the function
7/31/2019 1) Matlab_Miniguide
8/22
Oscar D. Crisalle 1997-2009 - 7 - MATLAB Miniguide
B =1 1 1
1 1 11 1 1
ones returns a square matrix.
>> C = zeros(2, 2)
C =0 00 0
Creates a matrix whose entries are all zeros.
>> C = zeros(2, 1)
C =0
0
>> C = zeros(size(A))
C =0 0 0
0 0 0
>> C = zeros(3)
C =0 0 0
0 0 00 0 0
>> D = eye(2, 2)
D =
1 00 1
Creates an identity matrix of order 2
>> D = eye(2, 3)
D = 1 0 00 1 0
The matrix does not have to be square for eye towork
>> D = eye(size(A))
D =1 0 00 1 0
>> D = eye(3)
D =1 0 0
0 1 00 0 1
1.4.3 Defining Transcendental Functions sin, cos, log, exp
>> pi = 4 * atan(1)
pi =3.1416
Defines = 4 arctan(1).
7/31/2019 1) Matlab_Miniguide
9/22
Oscar D. Crisalle 1997-2009 - 8 - MATLAB Miniguide
>> d = cos(pi)
d =
-1
cosine function
>> d = log10(100)
d =
2
Logarithm to base 10
>> d = log(100)
d =4.6052
Natural logarithm (base e)
1.4.4 Defining Basic Operations det, eig, conv, poly
>> A
A =
5 67 8
Displays matrix A
>> B = A'
B =
5 76 8
Transpose of matrix A. The apostrophe is usedto denote transposition, since it is common in
mathematics to use the nomenclature A to
denote AT>> C = A + B
C =10 13
13 16
Sum of two matrices
>> det(A)
ans =
-2
Determinant of matrix
>> C = inv(A)
C =-4 3
3.5 -2.5
Matrix inversion
>> C * A
ans =1 0
0 1
Matrix multiplication
>> D = abs( [-3, 4] )
D =
3 4
Absolute value of elements of row vector [-3, 4]
>> C = A^2
C =67 78
91 106
Find the second power of matrix A (i.e. A2)
>> eig(A) Finds the eigenvalues of matrix A
7/31/2019 1) Matlab_Miniguide
10/22
Oscar D. Crisalle 1997-2009 - 9 - MATLAB Miniguide
ans =-0.1521
13.1521
>> [H, L] = eig(A)
H =
-0.7587 -0.59280.6515 0.8054
L =
-0.1521 00 13.1521
Eigenvalues ofA are written in diagonal matrix
L =!1 0
0 !2
"
#$
%
&'
and eigenvectorsv1
andv2
arewritten in the columns of matrix H = v1 v2[ ],
where v1 =!0.7587
0.6515
"
#$%
&'and v2 =
-0.5928
-0.8054
!
"#
$
%&
>> b = [10; 20], C = [A, b]
b =1020
C =5 6 107 8 20
Augments matrix A with vector b to obtain C
>> i = sqrt(-1)
i =0 + 1i
Defines the imaginary unit i =!1
>> z = 3 + 4 * iz =
3 +4i
Defines a complex number z = 3 + 4 i.
>> z + (1 + 10 * i )
ans =
4 + 14i
Addition of complex numbers
>> p1 = [1, 0.3], ...
p2 = [1, 0.1]
p1 =1 0.3
p2 =
1 0.1
Defines polynomialsp1(s) = s + 0.3 and p2(s) = s + 0.1
The ellipsis (...) indicates that the commandcontinues on the next line
>> p3 = conv(p1, p2)
p3 = 1 0.4 0.03
Product of two polynomials (convolution)
p3(s) = p1(s) p2(s) = s2 + 0.4s + 0.03
>> p = [1 -6 11 -6], ...r = roots(p)
p =
1 -6 11 6r =
32
1
Define p(s) = s3 - 6s2 + 11s - 6 and find itsroots (s1 = 3, s2 = 2, and s3 = 1). The roots are
stored in column-vector r.
>> q = poly(r)
q =1 -6 11 -6
Creates polynomial q(s) which has roots
indicated by the entries of vector r = [3 2 1]T.
Here q(s) = s3 6s2 + 11s - 6
7/31/2019 1) Matlab_Miniguide
11/22
Oscar D. Crisalle 1997-2009 - 10 - MATLAB Miniguide
1.5 ADVANCED MATLAB COMMANDS
1.5.1 Plotting
x = [0:0.1:10];
y = sin(x);
plot(x, y);
Generates vector x with first component equal to
0 and last component equal to 10. Intermediate
components are spaced at intervals equal to 0.1
Calculates vector y
Generates a plot ofx versus y
0 2 4 6 8 10-1
-0.5
0
0.5
1
plot(x, y, '--') Generates a plot ofx versus y using dashed lines
0 2 4 6 8 10-1
-0.5
0
0.5
1
title('sine plot')xlabel('x')
7/31/2019 1) Matlab_Miniguide
12/22
Oscar D. Crisalle 1997-2009 - 11 - MATLAB Miniguide
ylabel('sin(x)')grid
0 2 4 6 8 10-1
-0.5
0
0.5
1s ne p o
x
s
n
x
help plot
Provides help on the "plot" command. See also:loglog, semilog, polar, text
print -dpdf FileName Saves the figure that is currently displayed as aPDF (portable document format) file with name
FileName.pdf
print -deps -tiff -r300 FileName Saves the figure that is currently displayed as a
color EPS (encapsulated PostScript) file withname FileName.eps that will print in a PostScript
printer with a resolution of 300 dpi. The default
resolution is 150 dpi. The option -tiffcreaters a 72 dpi preview that can be displayed in
a computer screen by many word processors that
import the file.
print -depsc -tiff -r300 FileName Same as above, except that the file is saved in acolor EPS format.
print dill FileName Saves the figure that is currently displayed to a
file with the name FileName.ai that is compatiblewith the Adobe Illustrator graphical software
package.
1.5.2 Displaying to the Screen
disp('Result') Displays the string "Result" on the screen
7/31/2019 1) Matlab_Miniguide
13/22
Oscar D. Crisalle 1997-2009 - 12 - MATLAB Miniguide
Result
disp('Result'),disp('------')
Result------
Displays the string "Result" on the screen
followed by a dashed underline
A = [1,2;3,4]
A =
1 23 4
Defines matrix A and echoes the result to the
screen
disp(A)1 23 4
Displays the entries of matrix A but does not
display the header line "A ="
1.5.3 Operating with Strings of Characters
s = 'This is a string'
s =
This is a string
Defines a string of characters and stores it in
variable s
disp(s)
This is a string
s1 = 'This is';s2 = ' a string';
s3 = [s1 s2]
s3 =
This is a string
Defines string s1Defines string s2
Defines string s3 as the concatenation of s1 and
s2
s1 = 'x is equal to ';
x = 17;s2 = num2str(x);
s3 = [s1 s2]
s3 =
Defines string s1Assigns a value to variable x
Changes the value numeric variable x to a string
of characters. NOTE: num2str only converts
only to four decimal places
7/31/2019 1) Matlab_Miniguide
14/22
Oscar D. Crisalle 1997-2009 - 13 - MATLAB Miniguide
x is equal to 17
disp(s3)
x is equal to 17
help disp See also: sprintf, fprintf, num2str, int2str
1.5.4 Appending Results to a Vector or a Matrix
x = []
x =
[]
x1 = [10;20]
x1 =
10
20
x2 = [100;200]
x2 =
100
200
x = [x; x1]
x =
10
20
x = [x;x1]
x =
102010
20
x = [x;x2;x2]
x =
1020
Defines an empty vector
Defines vector x1
Defines vector x2
Appends columns of x1 to x
Appends again columns of x1 to x
7/31/2019 1) Matlab_Miniguide
15/22
Oscar D. Crisalle 1997-2009 - 14 - MATLAB Miniguide
1020100
200100200
Appends columns of x2 twice to x
z = [1;10;100;1000]
z =1
10
1001000
y = log10(z);
y =
012
3
t = [z, y]
t =
1 010 1
100 21000 3
disp(' t y'); ...
disp('---- ---'); disp(t)
t y---- ---
1 010 1
100 2
1000 3
Creates a two-column matrix
1.5.5 Taking Input from the Keyboard
n = input('Give value of n ')
Give value of n
n =
3
Asks the user to give a value for n
If user enters "3" followed by return, the value of
n is displayed on the screen
7/31/2019 1) Matlab_Miniguide
16/22
Oscar D. Crisalle 1997-2009 - 15 - MATLAB Miniguide
1.5.6 Creating a Diary File
diary exercise1
x = [1 10 100]
x =
1 10 100
y = log10(x)
y =
0 1 2
diary off
Creates a file named 'exercise1' with the
following contents that contains all the linesdisplayed to the screen following the command
"diary". The file exercise1 has the followingcontents:
x = [1 10 100]
x =
1 10 100
y = log10(x)
y =
0 1 2
diary off
1.5.7. Creating an M-File
An M-file (or M-script) is a text file that contains MATLAB commands, and has the extension
.m. Create this text file using a text editor. Common text editors are: xedit, vi, and emacs.
x = [1 10 100]
y = log10(x)
Use a text editor to create and save a file (M-file)containing the two lines shown on the left
column. Save the file under the name 'test1.m'
test1
x =
1 10 100
y =
0 1 2
Execute 'test1.m' from the MATLAB command
window
7/31/2019 1) Matlab_Miniguide
17/22
Oscar D. Crisalle 1997-2009 - 16 - MATLAB Miniguide
1.5.8 If Structure
x = input('value of x ')
if x < 0
disp('x negative')
elseif x == 0
disp('s is equal to 0')
else
disp('s is positive')
end
Create an M-file entitled 'test2.m' containing the
lines shown on the left column.
The relational operators are:
== equal ~= not equal
< less than greater than >= greater than or equal
| logic or & logic and
To get help on these operators type
help relop
>>test2
value of x
x =3
x is positive
Execute 'test2.m' from the MATLAB command
window and input the value "3" in response to
the query.
1.5.9 While Structure
x = 1000
while x > 1
x = x / 10
end
Create an M-file entitled 'test3.m' containing thelines shown on the left column.
>>test3
x =1000
x =
100
x =
10
x =
Execute 'test3.m' from the MATLAB commandwindow
7/31/2019 1) Matlab_Miniguide
18/22
Oscar D. Crisalle 1997-2009 - 17 - MATLAB Miniguide
1
1.5.10 For Structure
for i = 5:-1:1
disp(i)
end
Create an M-file entitled 'test4.m' containing thelines shown on the left column.
>>test4
5
432
1
Execute 'test4.m' from the MATLAB commandwindow
1.5.11 Break Command
The break command forces the termination of a for loop or awhile loop.
x = [0:0.001:10]';y = sin(x);
n = length(y);
for i = 1 : n
if y(i) >= 0.95
x1 = x(i);break
end
end
disp(['sine is equal to 0.95 at
x = ' num2str(x1)])
Create an M-file entitled 'test5.m' containing thelines shown on the left column.
The break command exits the loop whenever the
line containing the word "break" is executed.
>>test5
sine is equal to 0.95 at x = 1.254
Execute 'test5.m' from the MATLAB commandwindow
7/31/2019 1) Matlab_Miniguide
19/22
Oscar D. Crisalle 1997-2009 - 18 - MATLAB Miniguide
1.5.12 M-Functions
M-functions are M-files that take inputs and return outputs.
function f = sqlog(x)
f = x^2 * log10(x);
return
Create an M-file entitled 'sqlog.m' containing the
lines shown on the left column.
The variable "f" appearing to the left of the equal
sign of the first line is the output, while the
variable "x" appearing on the right hand side isthe input to the function.
>>x = 1;
>>sqlog(x)
ans =
0
>>x=10; sqlog(x)
ans =
100
Assign the value of 1 to variable x.
Execute 'sqlog.m' from the MATLAB command
window.
function f = xsqylog(x, y) ;
f = x^2 * log10(y)
return
Create an M-file entitled 'xsqylog.m' containingthe lines shown on the left column. M-functions
can have multiple inputs.
>>xsqylog(3,100)
ans =
18
Execute 'xsqylog.m' from the MATLAB
command window.
function [f, g] = fsqglog(x)
f = x^2;g = log10(x);
return
Create an M-file entitled 'fsqglog.m' containing
the lines shown on the left column. M-functionscan have multiple outputs.
>>[f, g] = fsqglog(10)
f =100
g =
Execute 'fsqglog.m' from the MATLAB
command window.
7/31/2019 1) Matlab_Miniguide
20/22
Oscar D. Crisalle 1997-2009 - 19 - MATLAB Miniguide
1
7/31/2019 1) Matlab_Miniguide
21/22
Oscar D. Crisalle 1997-2009 - 20 - MATLAB Miniguide
1.5.13 Quadrature/Numerical Integration
The integration of functions can be done using the gaussian-quadrature function QUAD. This
function requires that the user define an M-function that calculates the integrand for any value of
the dummy integration variable. The example below calculates the integral (2x +1)ab! dx .
function f = integrand(x)
f = 2 * x + 1;
return
Create an M-file entitled 'integrand.m' containingthe lines shown on the left column.
>>a = 0; b = 1 ;>>quad('integrand', a, b)
ans =
2
Define integration limits
Call the QUAD function to integrate the functionintegrand.m between limits a to b
See also: quad8
7/31/2019 1) Matlab_Miniguide
22/22
1.5.14 ODE23/ODE45
ODE23/ODE45 are differential equation solvers. This section describes solvers that appeared in
earlier versions of MATLAB; consequently, these commands may be obsolete. On the other
hand, the newer solvers retain the basic ideas of the functions ODE23 or ODE45 described
below. The differential equation solved is of the form
dx/dt = f(t, x)
where f(t, x) is known informally as the right-hand-side function. The functions ODE23 and
ODE45 are ordinary differential equation solvers of variable orders 2-3 and 4-5, respectively.
They require that the user define an M-function that calculates the values of the right-hand-side
function f(x, t). The example below calculates the solution to the equation
dx/dt = t2 log(x)
with initial value xo = 2. The result is obtained for values of t ranging from to = 0 to tf= 4.
function f = dxdt(t,x)
f = -t^2 * log(x)
return
Create an M-file entitled 'dxdt.m' containing thelines shown on the left column.
>>t0 = 0; tf = 4;>>x0 = 2;
>>[t,x] = ode23('dxdt',t0,tf,x0);>>plot(t,x)>>xlabel('t')
>>ylabel('x')
0 1 2 3 40.8
1
1.2
1.4
1.6
1.8
2
t
x
Define initial and final times to and tf
Define initial condition xo
Call the ODE23 solver
Plot the solution