Upload
badro1980
View
223
Download
0
Embed Size (px)
Citation preview
8/7/2019 Matlab Miniguide
http://slidepdf.com/reader/full/matlab-miniguide 1/11
Chemical Engineering Department
University of Florida
© Oscar D. Crisalle 1997- 2007 File Name: Matlab_Miniguide_Rev_7.doc
MATLAB MINIGUIDE
CONTENTS
1.1 MATLAB Manuals and Literature...........................................................1
1.1.1 Manuals and Tutorials Available at CIRCA.................................1
1.1.2 Manuals Available in the Biery Room in Chemical Engineering..1
1.2 Introduction to MATLAB.........................................................................2
1.2.1 Modes of Using MATLAB..........................................................2
1.2.2 Executing the MATLAB Program ...............................................2
1.2.3 Exiting from the MATLAB Program ...........................................2
1.2.4 Obtaining On-Line Help ..............................................................2
1.2.5 Useful Keyboard Commands.......................................................31.2.6 Adjusting the Format of Numbers Displayed ...............................3
1.3 List of Essential Commands and Operators.............................................4
1.4 Overview of MATLAB Operations...........................................................5
1.4.1 Defining Vectors, Matrices and Polynomials ...............................5
1.4.2 Defining Three Useful Functions— ones, zeros, eye....................6
1.4.3 Defining Transcendental Functions— sin, cos, log, exp ...............7
1.4.4 Defining Basic Operations— det, eig, conv, poly.........................8
1.5 Advanced MATLAB Commands..............................................................10
1.5.1 Plotting........................................................................................10
1.5.2 Displaying to the Screen..............................................................11
1.5.3 Operating with Strings of Characters............................................12
1.5.4 Appending Results to a Vector or a Matrix ..................................12
1.5.5 Taking Input from the Keyboard..................................................14
1.5.6 Creating a Diary File....................................................................14
1.5.7. Creating an M-File.......................................................................15
1.5.8 If Structure...................................................................................15
1.5.9 While Structure............................................................................16
1.5.10 For Structure................................................................................16
1.5.11 Break Command..........................................................................17
1.5.12 M-Functions................................................................................17
1.5.13 Quadrature/Numerical Integration................................................19
1.5.14 ODE23/ODE45............................................................................20
8/7/2019 Matlab Miniguide
http://slidepdf.com/reader/full/matlab-miniguide 2/11
- 1 - MATLAB Miniguide
1.1 MATLAB MANUALS AND LITERATURE
Program name:
MATLAB (personal computers)
PRO-MATLAB (workstations)
Note: Manuals may be titled MATLAB 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
1.1.2 Manuals Available in the Biery Room in Chemical Engineering
A copy of the MATLAB and SIMULINK User's guides are available in the Biery
room. Please do not remove these manuals from the room.
- 2 - MATLAB Miniguide
1.2 INTRODUCTION TO MATLAB
MATLAB is a high-level computer language with powerful commands that emphasizenumerical 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 t he word “quit”; the symbol “>>” is the MATLAB prompt.
1.2.4 Obtaining On-Line Help
Type: >> help to get a list of commands
8/7/2019 Matlab Miniguide
http://slidepdf.com/reader/full/matlab-miniguide 3/11
- 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
- 4 - MATLAB Miniguide
1.3 LIST OF ESSENTIAL COMMANDS AND OPERATORS
The following commands must be thoroughly studied from the MATLAB manual (ortutorial) 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
8/7/2019 Matlab Miniguide
http://slidepdf.com/reader/full/matlab-miniguide 4/11
- 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 =123
Defines column vectorx =
1
2
3
!
"
###
$
%
&&&
The semicolon indicates that the next element ison a new row (the semicolon is an end-of-rowmarker)
>>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 67 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 of A and all columns of matrix A
>> b = A(:, 2)
b =68
Denotes all rows of A and column 2 of matrix A
- 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
>> poly2sy m([1 0.9 0.3], ‘s’)
ans =
s2 + 0.9s + 0.3
Transforms a row-vector polynomialrepresentation into a standard symbolic
representation shown the powers of the variable sand 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 11 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 97 8 10
B =1 1 11 1 1
More than one command can be given on a line,
by separating each individual command with acomma. Commands can also be embedded intoother commands.
The ellipsis (...) indicates that the commandcontinues on the next line
>> B = ones(3) When only one number is given, the function
8/7/2019 Matlab Miniguide
http://slidepdf.com/reader/full/matlab-miniguide 5/11
- 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 =00
>> C = zeros(size(A))
C =0 0 00 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).
- 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 used
to denote transposition, since it is common inmathematics to use the nomenclature A’ to
denote AT >> C = A + B
C =10 1313 16
Sum of two matrices
>> det(A)
ans =-2
Determinant of matrix
>> C = inv(A)
C =-4 33.5 -2.5
Matrix inversion
>> C * A
ans =
1 00 1
Matrix multiplication
>> D = abs( [-3, 4] )
D =3 4
Absolute value of elements of row vector [-3, 4]
>> C = A^2
C =67 7891 106
Find the second power of matrix A (i.e. A2)
>> eig(A) Finds the eigenvalues of matrix A
8/7/2019 Matlab Miniguide
http://slidepdf.com/reader/full/matlab-miniguide 6/11
- 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 of A are written in diagonal matrix
L =
! 1 0
0 ! 2
"
# $
%
& ' and eigenvectors v1 and v2 are
written 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 * i z =
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 polynomials
p1(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 6
r =321
Define p(s) = s3 - 6 s2 + 11s - 6 and find itsroots (s
1= 3, s
2= 2, and s
3= 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
- 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 to0 and last component equal to 10. Intermediatecomponents are spaced at intervals equal to 0.1
Calculates vector y Generates a plot of x versus y
0 2 4 6 8 10-1
-0.5
0
0.5
1
»plot(x, y, '--') Generates a plot of x versus y using dashed lines
0 2 4 6 8 10-1
-0.5
0
0.5
1
»title('sine plot')»xlabel('x')
8/7/2019 Matlab Miniguide
http://slidepdf.com/reader/full/matlab-miniguide 7/11
- 11 - MATLAB Miniguide
»ylabel('sin(x)')»grid
0 2 4 6 8 10-1
-0.5
0
0.5
1sine plot
x
sin(x)
»help plot Provides help on the "plot" command. See also:loglog, semilog, polar, text
1.5.2 Displaying to the Screen
»disp('Result')
Result
Displays the string "Result" on the screen
»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 thescreen
»disp(A)1 23 4
Displays the entries of matrix A but does not
display the header line "A ="
- 12 - MATLAB Miniguide
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 invariable 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 s2Defines string s3 as the concatenation of s1 ands2
»s1 = 'x is equal to ';»x = 17;»s2 = num2str(x);
»s3 = [s1 s2]
s3 =
x is equal to 17
»disp(s3)
x is equal to 17
Defines string s1Assigns a value to variable xChanges the value numeric variable x to a stringof characters. NOTE: num2str only convertsonly to four decimal places
»help disp See also: sprintf, fprintf, num2str, int2str
1.5.4 Appending Results to a Vector or a Matrix
»x = []
x =
[]
Defines an empty vector
8/7/2019 Matlab Miniguide
http://slidepdf.com/reader/full/matlab-miniguide 8/11
- 13 - MATLAB Miniguide
»x1 = [10;20]
x1 =
1020
»x2 = [100;200]
x2 =
100200
»x = [x; x1]
x =
1020
»x = [x;x1]
x =
10201020
»x = [x;x2;x2]
x =
10201020100200100200
Defines vector x1
Defines vector x2
Appends columns of x1 to x
Appends again columns of x1 to x
Appends columns of x2 twice to x
»z = [1;10;100;1000]
z =1101001000
»y = log10(z);
y =012
- 14 - MATLAB Miniguide
3
»t = [z, y]
t =
1 010 1100 21000 3
»disp(' t y'); ...disp('---- ---'); disp(t)
t y---- ---
1 010 1100 21000 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
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 thefollowing contents that contains all the lines
displayed to the screen following the command
"diary". The file exercise1 has the followingcontents:
x = [1 10 100]
x =
1 10 100
y = log10(x)
8/7/2019 Matlab Miniguide
http://slidepdf.com/reader/full/matlab-miniguide 9/11
- 15 - MATLAB Miniguide
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 leftcolumn. 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
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 thelines shown on the left column.
The relational operators are:
== equal ~= not equal< less than <= less than or equal> greater than >= greater than or equal| logic or & logic and
To get help on these operators type
» help relop
- 16 - MATLAB Miniguide
>>test2
value of x
x =3
x is positive
Execute 'test2.m' from the MATLAB command
window and input the value "3" in response tothe 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 =1
Execute 'test3.m' from the MATLAB commandwindow
1.5.10 For Structure
for i = 5:-1:1
disp(i)
end
Create an M-file entitled 'test4.m' containing the
lines shown on the left column.
>>test4
54321
Execute 'test4.m' from the MATLAB commandwindow
8/7/2019 Matlab Miniguide
http://slidepdf.com/reader/full/matlab-miniguide 10/11
- 17 - MATLAB Miniguide
1.5.11 Break Command
The break command forces the termination of a for loop or a while 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 atx = ' num2str(x1)])
Create an M-file entitled 'test5.m' containing thelines shown on the left column.
The break command exits the l oop whenever theline containing the word "break" is executed.
>>test5
sine is equal to 0.95 at x = 1.254
Execute 'test5.m' from the MATLAB commandwindow
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 thelines shown on the left column.
The variable "f" appearing to the left of the equalsign of the first line is the output, while thevariable "x" appearing on the right hand side isthe input to the function.
>>x = 1;
>>sqlog(x)
ans =
0
>>x=10; sqlog(x)
Assign the value of 1 to variable x.
Execute 'sqlog.m' from the MATLAB commandwindow.
- 18 - MATLAB Miniguide
ans =
100
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-functionscan have multiple inputs.
>>xsqylog(3,100)
ans =
18
Execute 'xsqylog.m' from the MATLABcommand 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 =1
Execute 'fsqglog.m' from the MATLABcommand window.
8/7/2019 Matlab Miniguide
http://slidepdf.com/reader/full/matlab-miniguide 11/11
- 19 - 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)a
b
! 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 limitsCall the QUAD function to integrate the functionintegrand.m between limits a to b
See also: quad8
- 20 - MATLAB Miniguide
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