You are on page 1of 11

Chemical Engineering Department

University of Florida
1.5.13 Quadrature/Numerical Integration................................................ 19
1.5.14 ODE23/ODE45............................................................................ 20

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 ....................................................... 3
1.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

© Oscar D. Crisalle 1997- 2007 File Name: Matlab_Miniguide_Rev_7.doc


1.2 INTRODUCTION TO MATLAB
1.1 MATLAB MANUALS AND LITERATURE
MATLAB is a high-level computer language with powerful commands that emphasize
Program name: numerical operations with matrices. The word MATLAB itself is derived from the words
MATrix LABoratory. Originally MATLAB carried out only linear algebra calculations (matrix
MATLAB (personal computers)
operations) but has now been extended to include operations useful for signal processing, control
PRO-MATLAB (workstations) 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:
Note: Manuals may be titled MATLAB or PRO-MATLAB. • Control toolbox • Robust control toolbox
• Identification toolbox • MFD (multivariable frequency design) toolbox
Basic manuals an documentation: • Optimization toolbox • Splines toolbox

a. MATLAB user's guide (tutorial and reference) The related program SIMULINK includes MATLAB plus additional capabilities for
b. Control Toolbox manual simulating nonlinear dynamic systems. MATLAB is available in almost all computer platforms
c. SIMULINK Manual (IBM, Macintosh, HP, Sun, DEC). All commands remain unchanged from one computer to
d. Various manuals for each toolbox another.

1.1.1 Manuals and Tutorials Available at CIRCA 1.2.1 Modes of Using MATLAB

a. CIRCA Lab: a. Interactive (commands issued using a keyboard).


b. M-files (programs) , which can be of three types: (1) M-scripts (also called M-files),
Room: CSE 211 - Phone: 392-2446
(2) M-functions, and (3) SIMULINK M-files.
Hours: M-F 8:00 AM - midnight Sat. Noon - Midnight
1.2.2 Executing the MATLAB Program
b. CIRCA consultants office
Type: matlab
Room: CSE 520 - Phone: 2-HELP (2-4357)
Hours: M-F 9:00 AM - 5:00 PM The prompt >> appears, indicating that MATLAB is ready to receive interactive
commands.
1.1.2 Manuals Available in the Biery Room in Chemical Engineering
1.2.3 Exiting from the MATLAB Program
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. 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

-1- MATLAB Miniguide -2- MATLAB Miniguide


Example: to get help on the command dir type: >> help dir 1.3 LIST OF ESSENTIAL COMMANDS AND OPERATORS

Type: >> demo to get a demonstration of some of MATLAB's features. The following commands must be thoroughly studied from the MATLAB manual (or
tutorial) so you may carry out the essential operations available.
1.2.5 Useful Keyboard Commands
• diary

! Repeats previous command • save, load

" Advances to next command • help

# Move left on command line • who, whos, size, dir, clear

$ Move right on command line • inv

^a Move to beginning of command line • eig

^e Move to end of command line • zeros, ones, eye

^d Delete next character • conv

Backspace Delete previous character • roots

1.2.6 Adjusting the Format of Numbers Displayed • format short, format compact, format short e

• plot, hold, axis, title, text, shg, clg, semilog, loglog, subplot
format short shows 5 digits
• %
format short e shows 5 digits in exponential form
• ' (apostrophe)
format long shows 15 digits
• : (colon)
format long e shows 15 digits in exponential form
• ; (semicolon)
format compact does not display extra blank line after each answer is
• , (comma)
echoed
All of these commands must be typed in lowercase (MATLAB is case-sensitive).

To learn more about a command, type help. Example: >> help whos

-3- MATLAB Miniguide -4- MATLAB Miniguide


1.4 OVERVIEW OF MATLAB OPERATIONS >> b = A(1, 1) + A(2, 2) Sum of elements (1, 1) and (2, 2) of matrix A
b =
1.4.1 Defining Vectors, Matrices and Polynomials 13
>> A(1, 1) + A(2, 2) Sum of elements (1, 1) and (2, 2) of matrix A
!1 $ ans =
Defines column vector x = ## 2 &&
>> x = [ 1 The result is written to the default variable ans
13
2
3] >> p = [1 0.9 0.3] Denotes the polynomial
#" 3 &%
p = p(s) = s2 + 0.9s + 0.3
x = 1 0.9 0.3 Polynomials are represented as row vectors.
Echo displayed on the screen
1 >> size(A) Finds the number of rows and columns
2
3 of matrix A
ans =
!1 $ 2 2
Defines column vector x = ## 2 &&
>> x = [1; 2; 3] >> poly2sym([1 0.9 0.3], ‘s’) Transforms a row-vector polynomial
representation into a standard symbolic
#" 3 &% ans =
representation shown the powers of the variable s
s2 + 0.9s + 0.3
x = The semicolon indicates that the next element is and all the terms in the polynomial (requires that
1 on a new row (the semicolon is an end-of-row the Symbolic Toolbox be installed)
2 marker) >> size(p)
3 Finds the number of rows and columns
>>x = [1 2 3] Defines row vector x = [1 2 3] of vector p
ans =
1 3
x = >> who
1 2 3 Echo printed on screen List all variables currently defined
>> x = [1, 2, 3] Defines row vector x = [1 2 3 ] Your variables are:
The comma indicates that the next element is on A ans b p x
x =
1 2 3 a new column ( the comma is an end-of-column
marker) 1.4.2 Defining Three Useful Functions— ones, zeros, eye
>> A = [5 6 Defines matrix A
7 8]
A =
5 6 >> B = ones(2, 2) Create a matrix consisting of 2 rows and 2
7 8 columns, and whose entries are all equal to 1
>> A = [5, 6; 7, 8] Defines matrix A B =
1 1
A = 1 1
5 6 The comma separates elements on the same row, >>B = ones(2, 1) Create a matrix consisting of 2 rows and 1
7 8 and the semicolon separates elements on column, and whose entries are all equal to 1
different rows B =
>> b = A(2, 2) 1
Denotes the element (2, 2) of matrix A 1
b =
8 >> A = [5 6 9; 7 8 10], ... More than one command can be given on a line,
>> b = A(2, :) B = ones(size(A))
Denotes row 2 of A and all columns of matrix A by separating each individual command with a
A = comma. Commands can also be embedded into
b =
7 8 5 6 9 other commands.
>> b = A(:, 2) 7 8 10
Denotes all rows of A and column 2 of matrix A B = The ellipsis (...) indicates that the command
b = 1 1 1
1 1 1 continues on the next line
6
8 >> B = ones(3) When only one number is given, the function

-5- MATLAB Miniguide -6- MATLAB Miniguide


ones returns a square matrix. >> d = cos(pi) cosine function
B =
1 1 1 d =
1 1 1 -1
1 1 1 >> d = log10(100) Logarithm to base 10
>> C = zeros(2, 2) Creates a matrix whose entries are all zeros.
d =
C = 2
0 0 >> d = log(100) Natural logarithm (base e)
0 0
>> C = zeros(2, 1) d =
4.6052
C =
0
0 1.4.4 Defining Basic Operations— det, eig, conv, poly
>> C = zeros(size(A))

C = >> A
0 0 0 Displays matrix A
0 0 0
A =
>> C = zeros(3) 5 6
7 8
C = >> B = A'
0 0 0 Transpose of matrix A. The apostrophe is used
0 0 0 to denote transposition, since it is common in
B =
0 0 0
5 7 mathematics to use the nomenclature A’ to
>> D = eye(2, 2) Creates an identity matrix of order 2 6 8 denote AT
>> C = A + B Sum of two matrices
D =
1 0
C =
0 1
10 13
>> D = eye(2, 3) The matrix does not have to be square for eye to 13 16
work >> det(A) Determinant of matrix
D =
1 0 0
ans =
0 1 0
-2
>> D = eye(size(A))
>> C = inv(A) Matrix inversion
D =
C =
1 0 0
-4 3
0 1 0
3.5 -2.5
>> D = eye(3)
>> C * A Matrix multiplication
D =
ans =
1 0 0
1 0
0 1 0
0 1
0 0 1
>> D = abs( [-3, 4] ) Absolute value of elements of row vector [-3, 4]
1.4.3 Defining Transcendental Functions— sin, cos, log, exp D =
3 4
>> C = A^2 Find the second power of matrix A (i.e. A2)
>> pi = 4 * atan(1) Defines % = 4 arctan(1). C =
67 78
pi = 91 106
3.1416 >> eig(A) Finds the eigenvalues of matrix A

-7- MATLAB Miniguide -8- MATLAB Miniguide


1.5 ADVANCED MATLAB COMMANDS
ans =
-0.1521
13.1521 1.5.1 Plotting
>> [H, L] = eig(A) Eigenvalues of A are written in diagonal matrix
"!1 0%
L=$ and eigenvectors v1 and v 2 are
!2 '&
H =
-0.7587 -0.5928 #0
»x = [0:0.1:10];
0.6515 0.8054 written in the columns of matrix H = [v1 v 2 ] , Generates vector x with first component equal to
L = 0 and last component equal to 10. Intermediate
"!0.7587% !-0.5928$
-0.1521 0 where v1 = $ and v 2 = #
0 13.1521 # 0.6515 '& "-0.8054&% components are spaced at intervals equal to 0.1
»y = sin(x);
>> b = [10; 20], C = [A, b] Augments matrix A with vector b to obtain C »plot(x, y);
Calculates vector y
b = Generates a plot of x versus y
10
20 1
C =
5 6 10
7 8 20
0.5
>> i = sqrt(-1) Defines the imaginary unit i = !1
i =
0 + 1i
0
>> z = 3 + 4 * i Defines a complex number z = 3 + 4 i.
z = -0.5
3 +4i
>> z + (1 + 10 * i ) Addition of complex numbers
ans = -1
4 + 14i 0 2 4 6 8 10
>> p1 = [1, 0.3], ... Defines polynomials
p2 = [1, 0.1]
»plot(x, y, '--') Generates a plot of x versus y using dashed lines
p1(s) = s + 0.3 and p2(s) = s + 0.1
p1 =
1 0.3 The ellipsis (...) indicates that the command 1
p2 = continues on the next line
0.1 1
>> p3 = conv(p1, p2) Product of two polynomials (convolution) 0.5
p3 = 1 0.4 0.03
p3(s) = p1(s) p2(s) = s2 + 0.4s + 0.03
>> p = [1 -6 11 -6], ... Define p(s) = s3 - 6s2 + 11s - 6 and find its
r = roots(p) 0
roots (s1 = 3, s2 = 2, and s3 = 1). The roots are
p = stored in column-vector r.
1 -6 11 6
r = -0.5
3
2
1
>> q = poly(r) -1
Creates polynomial q(s) which has roots 0 2 4 6 8 10
q = indicated by the entries of vector r = [3 2 1]T.
1 -6 11 -6 Here q(s) = s3 – 6s2 + 11s - 6 »title('sine plot')
»xlabel('x')

-9- MATLAB Miniguide - 10 - MATLAB Miniguide


»ylabel('sin(x)') sine plot 1.5.3 Operating with Strings of Characters
»grid 1

0.5 »s = 'This is a string' Defines a string of characters and stores it in


s = variable s

sin(x)
0 This is a string

-0.5 »disp(s)

This is a string

-1
0 2 4 6 8 10 »s1 = 'This is';
x Defines string s1
»s2 = ' a string';
»s3 = [s1 s2] Defines string s2
»help plot Provides help on the "plot" command. See also: Defines string s3 as the concatenation of s1 and
loglog, semilog, polar, text s3 = s2
This is a string
1.5.2 Displaying to the Screen
»s1 = 'x is equal to ';
Defines string s1
»x = 17;
»s2 = num2str(x); Assigns a value to variable x
»disp('Result')
Displays the string "Result" on the screen Changes the value numeric variable x to a string
of characters. NOTE: num2str only converts
Result
»s3 = [s1 s2]
only to four decimal places

»disp('Result'),disp('------') s3 =
Displays the string "Result" on the screen
Result followed by a dashed underline x is equal to 17
------
»disp(s3)

»A = [1,2;3,4] x is equal to 17
Defines matrix A and echoes the result to the
A = screen
»help disp
See also: sprintf, fprintf, num2str, int2str
1 2
3 4
1.5.4 Appending Results to a Vector or a Matrix
»disp(A)
Displays the entries of matrix A but does not
1 2
3 4 display the header line "A ="
»x = []
Defines an empty vector
x =

[]

- 11 - MATLAB Miniguide - 12 - MATLAB Miniguide


»x1 = [10;20] Defines vector x1 3

x1 = »t = [z, y]

10 t = Creates a two-column matrix


20
1 0
»x2 = [100;200] 10 1
100 2
x2 = Defines vector x2 1000 3

100 »disp(' t y'); ...


200 disp('---- ---'); disp(t)

»x = [x; x1] t y
---- ---
x = 1 0
Appends columns of x1 to x 10 1
10 100 2
20 1000 3

»x = [x;x1]

x = 1.5.5 Taking Input from the Keyboard


Appends again columns of x1 to x
10
20
10
»n = input('Give value of n ')
20 Asks the user to give a value for n
»x = [x;x2;x2] Give value of n

x = n = If user enters "3" followed by return, the value of


3
n is displayed on the screen
10
20 Appends columns of x2 twice to x
10
20 1.5.6 Creating a Diary File
100
200
100
200
»diary exercise1
Creates a file named 'exercise1' with the
»z = [1;10;100;1000] »x = [1 10 100] following contents that contains all the lines
displayed to the screen following the command
z = x = "diary". The file exercise1 has the following
1
10 1 10 100
contents:
100
1000 »y = log10(x) x = [1 10 100]

»y = log10(z); y = x =

y = 0 1 2 1 10 100
0
1 »diary off y = log10(x)
2

- 13 - MATLAB Miniguide - 14 - MATLAB Miniguide


y =
>>test2 Execute 'test2.m' from the MATLAB command
0 1 2
value of x window and input the value "3" in response to
diary off the query.
x =
3

1.5.7. Creating an M-File x is positive

An M-file (or M-script) is a text file that contains MATLAB commands, and has the extension
1.5.9 While Structure
.m. Create this text file using a text editor. Common text editors are: xedit, vi, and emacs.

x = 1000 Create an M-file entitled 'test3.m' containing the


x = [1 10 100]
Use a text editor to create and save a file (M-file)
while x > 1 lines shown on the left column.
y = log10(x) containing the two lines shown on the left
column. Save the file under the name 'test1.m' x = x / 10

end
»test1
Execute 'test1.m' from the MATLAB command >>test3 Execute 'test3.m' from the MATLAB command
x = window window
x =
1000
1 10 100
x =
y = 100
0 1 2 x =
10

x =
1.5.8 If Structure 1

1.5.10 For Structure

x = input('value of x ') Create an M-file entitled 'test2.m' containing the


lines shown on the left column. for i = 5:-1:1 Create an M-file entitled 'test4.m' containing the
if x < 0
disp(i) lines shown on the left column.
disp('x negative')
The relational operators are: end
elseif x == 0

disp('s is equal to 0') == equal ~= not equal >>test4


< less than <= less than or equal Execute 'test4.m' from the MATLAB command
else > greater than >= greater than or equal 5 window
| logic or & logic and 4
disp('s is positive') 3
2
end To get help on these operators type 1

» help relop

- 15 - MATLAB Miniguide - 16 - MATLAB Miniguide


1.5.11 Break Command ans =

100
The break command forces the termination of a for loop or a while loop.
function f = xsqylog(x, y) ; Create an M-file entitled 'xsqylog.m' containing
x = [0:0.001:10]'; f = x^2 * log10(y) the lines shown on the left column. M-functions
Create an M-file entitled 'test5.m' containing the can have multiple inputs.
y = sin(x);
n = length(y); lines shown on the left column. return

for i = 1 : n The break command exits the loop whenever the


line containing the word "break" is executed. >>xsqylog(3,100) Execute 'xsqylog.m' from the MATLAB
if y(i) >= 0.95
ans = command window.
x1 = x(i);
break 18
end function [f, g] = fsqglog(x) Create an M-file entitled 'fsqglog.m' containing
end f = x^2; the lines shown on the left column. M-functions
g = log10(x); can have multiple outputs.
disp(['sine is equal to 0.95 at
x = ' num2str(x1)]) return

>>test5 >>[f, g] = fsqglog(10) Execute 'fsqglog.m' from the MATLAB


Execute 'test5.m' from the MATLAB command
sine is equal to 0.95 at x = 1.254 window f = command window.
100

g =
1.5.12 M-Functions 1
M-functions are M-files that take inputs and return outputs.

function f = sqlog(x) Create an M-file entitled 'sqlog.m' containing the


f = x^2 * log10(x); lines shown on the left column.

return 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 is
the input to the function.

>>x = 1; Assign the value of 1 to variable x.


>>sqlog(x)
Execute 'sqlog.m' from the MATLAB command
ans = window.
0

>>x=10; sqlog(x)

- 17 - MATLAB Miniguide - 18 - MATLAB Miniguide


1.5.13 Quadrature/Numerical Integration 1.5.14 ODE23/ODE45

The integration of functions can be done using the gaussian-quadrature function QUAD. This ODE23/ODE45 are differential equation solvers. This section describes solvers that appeared in
function requires that the user define an M-function that calculates the integrand for any value of earlier versions of MATLAB; consequently, these commands may be obsolete. On the other
b
the dummy integration variable. The example below calculates the integral !a (2x + 1)dx . hand, the newer solvers retain the basic ideas of the functions ODE23 or ODE45 described
function f = integrand(x) Create an M-file entitled 'integrand.m' containing below. The differential equation solved is of the form
the lines shown on the left column.
f = 2 * x + 1;
dx/dt = f(t, x)
return
where f(t, x) is known informally as the right-hand-side function. The functions ODE23 and
>>a = 0; b = 1 ; Define integration limits
>>quad('integrand', a, b) ODE45 are ordinary differential equation solvers of variable orders 2-3 and 4-5, respectively.
Call the QUAD function to integrate the function
ans = integrand.m between limits a to b 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
2 See also: quad8
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) Create an M-file entitled 'dxdt.m' containing the
lines shown on the left column.
f = -t^2 * log(x)

return

>>t0 = 0; tf = 4;
Define initial and final times to and tf
>>x0 = 2;
Define initial condition xo
>>[t,x] = ode23('dxdt',t0,tf,x0);
>>plot(t,x) Call the ODE23 solver
>>xlabel('t') Plot the solution
>>ylabel('x')
2

1.8

1.6

1.4

x
1.2

0.8
0 1 2 3 4
t

- 19 - MATLAB Miniguide - 20 - MATLAB Miniguide

You might also like