BEGINNING
MATLAB
Machine Code
MATLAB High Level Programming Language
Assembly
Fortran C C++
BASIC JAVA
MATLAB
Easy Development
Efficient
Operation
MATLAB
CHAPTER 1
An Overview of MATLAB
MATLAB : Chapter 1. An Overview of MATLAB
References
1. Co So Matlab va Ung dung,
Author: Pham Thi Ngoi Yen
Publisher: Nha xuat ban Khoa hoc va Ky thuat, Ha Noi.
Year: 2006
2. The MATLAB Help System
3. Essential MATLAB for Engineers and Scientists
Author: Brian D. Hahn and Daniel T. Valentine
Publisher: Elsivier
Year: 2007
MATLAB : Chapter 1. An Overview of MATLAB
Starting Matlab
The default MATLAB Desktop.
MATLAB : Chapter 1. An Overview of MATLAB
Operations (1/2)
Symbol Operation MATLAB form
^ exponentiation: a^b
* multiplication: a*b
/ right division: a/b
\ left division: a\b
+ addition: a+b
 subtraction: ab
b
a
ab
a/ b
b a+
b a
b
a
=
b \ a
a
b
=
Scalar arithmetic operations
MATLAB : Chapter 1. An Overview of MATLAB
Operations (2/2)
Calculation result is saved
to ans by default : ans = 9
6 is saved to ans by using ans one
more time
1.5 is saved to the variable a by
assign a as the storing place
In the Matlab, \ = \
MATLAB : Chapter 1. An Overview of MATLAB
assignment , workspace, and command
The sign = is called the
assignment or replacement
operator.
e.g.
x = 3 : assign the value 3 to the variable x
x = x + 2 : add 2 to the current value of x
Workspace : the names and values of
any variables in use in the
current work session
Commands for managing the work
session
clc
clears the Command window
clear
Removes all variables from
memory
exist(name)
Determines if a file or variable
exists having the name name
quit
Stops MATLAB
who
Lists the variable currently in
memory
whos
Lists the current variables and
sizes, and indicates if they have
imaginary parts
:
Colon; generates and array
having regularly spaced
elements
,
Comma; separates elements of
an array
;
Semicolon; suppresses screen
printing; also denotes a new row
in an array
Ellipsis; continues a line
MATLAB : Chapter 1. An Overview of MATLAB
recall feature, and special variable
recall feature
recall a previously typed function or variable
e.g.
uparrow key() & downarrow key(): move up and down through the
previously typed lines one line at a time.
Tab key: automatically completes the name of a function, variable, or file if you
type the first few letters of the name and press the Tab key.
Special variables and constants
ans
Temporary variable containing the most recent answer
eps
Specifies the accuracy of floating point precision
i , j
The imaginary unit
Inf
Infinity
NaN
Indicates an undefined numerical result
pi
The number
1
MATLAB : Chapter 1. An Overview of MATLAB
Complex Number Operations
; is a command which
leads to a new line, also
omits calculation results.
MATLAB : Chapter 1. An Overview of MATLAB
Formatting Commands
The Format command controls how numbers appear on the screen.
format short
Four decimal digits (the default); 13.6745
format long
16 digits; 17.27484029463547
format short e
Five digits (four decimals) plus exponent; 6.3793e+03
format long e
16 digits (15 decimals) plus exponent; 6.379243784781294e04
format bank
Two decimal digits; 126.73
format +
Positive, negative, or zero; +
format rat
Rational approximation; 43/7
format compact
Suppresses some line feeds
format loose
Resets to less compact display mode
MATLAB : Chapter 1. An Overview of MATLAB
Array(1/2)
One of the strengths of MATLAB is its ability to handle collections of
numbers, called arrays .
A numerical array is an ordered collection of numbers
We can use square brackets
e.g.
>> x = [0, 1, 3, 6]
You need not type all the numbers in the array if they are regularly
spaced
e.g.
>> u = [0: 0.1: 10] u = [0, 0.1, 0.2, 0.3, , 9.8, 9.9, 10]
MATLAB : Chapter 1. An Overview of MATLAB
Array(2/2)
You can compute w=5*sin (u) for u=[0: 0.1: 10]
>> u=[0: 0.1: 10];
>> w=5*sin(u);
computed the formula w=5*sin(u) 101 times.
array index: points to a particular element in the array
>>u(7)
ans =
0.6000
>>w(7)
ans =
2.8232
length: determine how many values are in an array
>>m = length(w)
m =
101
MATLAB : Chapter 1. An Overview of MATLAB
Mathematical functions
Some commonly used
mathematical functions
Function MATLAB syntax()
exp(x)
sqrt(x)
log(x)
log10(x)
cos(x)
sin(x)
tan(x)
acos(x)
asin(x)
atan(x)
The MATLAB trigonometric functions
use radian measure
x
e
x
x ln
x l og
10
x cos
x sin
x tan
x cos
 1
x sin
 1
x tan
 1
MATLAB : Chapter 1. An Overview of MATLAB
Working with Files
Mfile: MATLAB function files and program files are saved with the
extension .m, and called Mfiles.
MATfile: save the names and values of variables .
ASCIIfile: files written in a specific format designed to make them
usable to a wide variety of software.
MATLAB : Chapter 1. An Overview of MATLAB
System, directory, and file commands
system, directory, and file commands
addpath dirname
Adds the directory dirname to the search path.
cd dirname
Changes the current directory to dirname.
dir
Lists all files in the current directory.
dir dirname
Lists all the files in the directory dirname.
path
Displays the MATLAB search path.
pathtool
Starts the Set Path tool.
pwd
Displays the current directory.
rmpath dirname
Removes the directory dirname from the search path.
what
Lists the MATLABspecific files found in the current working directory. Most data
files and other nonMATLAB files are not listed. Use dir to get a list of all files.
what dirname
Lists the MATLABspecific files in directory dirname.
MATLAB : Chapter 1. An Overview of MATLAB
Plotting commands
Some MATLAB plotting commands
[x , y] = ginput(n)
Enables the mouse to get n points from a plot, and returns the x and
y coordinates in the vectors x and y, which have a length n.
grid
puts grid lines on the plot.
gtext (text)
Enables placement of text with the mouse.
plot (x , y)
Generates a plot of the array y versus the array x on rectilinear axes.
title (text)
Puts text in a title at the top of the plot.
xlabel (text)
Adds a text label to the horizontal axis (the abscissa).
ylabel (text)
Adds a text label to the vertical axis (the ordinate).
MATLAB : Chapter 1. An Overview of MATLAB
Plotting with MATLAB
Variable pairs must be written.
(x,y) and (x,z) are pairs,
so express plot(x,y,x,z)
MATLAB : Chapter 1. An Overview of MATLAB
Linear Algebra Equations
the left division operator(\)
e.g.
64 9z  8y 2x
5 3z 2y  7x
70 4z 12y 6x
= +
= +
= + +
Matlabs basic unit is matrix
MATLAB : Chapter 1. An Overview of MATLAB
Statistics, Calculus, and Processing
Statistics
perform statistical calculations and other types of data
manipulation.
Numerical Calculus, Differential Equations, and Simulink
MATLAB can numerically compute the derivative and
the integral
Symbolic Processing
obtain the derivative and the integral in
symbolic form (a formula instead of as a set of numerical
values)
dy/dx
}
dx y
dy/dx
}
dx y
MATLAB : Chapter 1. An Overview of MATLAB
Script Files and the Editor/Debugger(1/2)
Two ways for performing operations in MATLAB
Interactive mode
: directly enter the commands in the Command window
using script files (commands files)
: store the commands in script files
Mfiles
script files
:when need to use many commands or arrays with
many elements
function files
:when need to repeat the operation of a set of
commands
MATLAB : Chapter 1. An Overview of MATLAB
Script Files and the Editor/Debugger(2/2)
Mfile make and save
MATLAB : Chapter 1. An Overview of MATLAB
Input/output commands
disp (A)
Displays the contents, but not the name, of the array A.
disp (text)
Displays the text string enclosed within single quotes.
format
Controls the screens output display format
fprintf
Performs formatted writes to the screen or to a file
x = input (text)
Displays the text in quotes, waits for user input from the
keyboard, and stores the value in x.
x = input (text , s)
Displays the text in quotes, waits for user input from the
keyboard, and stores the input as a string in x
k = menu
(title,option1,option2,)
Displays a menu whose title is in the string variable title,
and whose choices are option1,option2, and so on.
MATLAB : Chapter 1. An Overview of MATLAB
The MATLAB Help System(1/4)
Help Browser
Graphical user interface
find information, view online documentation
Help Functions
help, lookfor, doc
display syntax information for specified function
Other Resources
run demos, contact technical support, participate in a newsgroup.
The MathWorks Website
the home of MATLAB.
http://www.mathworks.com
MATLAB : Chapter 1. An Overview of MATLAB
The MATLAB Help System(2/4)
 Help Browser
The MATLAB Help Browser
Contents: a
contents listing tab
Index: a global
index tab
Search: a search
tab having a find
function and full
text search features
Demos: a
bookmaking tab to
start builtin
demonstrations
MATLAB : Chapter 1. An Overview of MATLAB
The MATLAB Help System(3/4)
 Help Functions
MATLAB Help functions (help, lookfor, doc)
Function Use
doc Displays the start page of the documentation in the Help Browser
doc function Displays the documentation for the MATLAB function function
doc toolbox/function Displays the documentation for the specified toolbox function
doc toolbox Displays the documentation road map page for the specified toolbox
help Displays a list all the function directories, with a description of the
function category each represents.
help function Displays in the Command window a description of the specified
function function
helpwin topic Displays the help text for the specified topic inside the desktop Help
Browser window
lookfor topic Displays in the Command window a brief description for all functions
whose description includes the specified keyword topic
type filename Displays the Mfile filename without opening it with a text editor.
MATLAB : Chapter 1. An Overview of MATLAB
The MATLAB Help System(4/4)
 Help Functions
Examples
28
MATLAB
CHAPTER 2
Numeric, Cell, and Structure Arrays
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
29
Arrays
Arrays : Collection of numbers
the basic building block in MATLAB
addition, subtraction, multiplication, division, and exponentiation
polynomial algebra and root
Available classes of arrays in MATLAB 7
numeric arrays : contains only numeric values
cell arrays : access data by its location
structure arrays : access data by name
Array
numeric character logical cell structure
function
handle
Java
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
30
Arrays
Cartesian coordinates x, y, and z
unit vector i, j, k
express the vector p = xi + yj + zk
e.g.
p = 5i + 7j + 2k
in MATLAB: write in a specific order,
separate with a space,
identify the group with brackets
[5 7 2]
vector
row vector [5 7 2]
column vector
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
31
Arrays
Creating Vectors in MATLAB
MATLAB displays row vectors horizontally and column vectors vertically.
Create a row vector : space or commas separate elements
g = [3 7 9] = [3,7,9]
Create a column vector : semicolon or Enter separate elements, you can use
transpose
g = [3;7;9] = [3,7,9] = [3 (Enter)
7 (Enter)
9]
Create vectors by appending
r = [2, 4, 20], w = [9, 6, 3]
u = [r, w] = [2, 4, 20, 9, 6, 3]
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
32
Arrays
Creating Vectors in MATLAB
Generate a large vector of regularly spaced elements using colon operator (:)
x = [m:q:n]
m : the first value
q : the increment (default = 1)
n : the last value <= n
x = [0:2:8] = [0, 2, 4, 6, 8] x = [0:2:7] = [0, 2, 4, 6]
y = [3:2] = [3, 2, 1, 0, 1, 2]
u = [10:2:4] = [10, 8, 6, 4]
The linspace command, logspace command
linspace(x1, x2, n) : n is number of points between x1 and x2
linspace(5,8,31) = [5:0.1:8]
logspace(a, b, n) : n is number of points between 10
a
and 10
b
logspace(1,1,4) = [0.1000, 0.4642, 2.1544, 10.000]
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
33
Arrays
TwoDimensional Arrays
An array can have multiple rows, multiple columns, or both
called a matrix
.
Creating Matrices
Space or commas separate elements in different columns
Semicolons separate elements in different rows
You can also create a matrix from row or column vectors
<example (a = [1,3,5], b=[7,9,11]) >
(
=
7 3 16
10 4 2
M
[1, 3, 5; 7, 9, 11]
[a; b]
[a b]
(
11 9 7
5 3 1
  11 9 7 5 3 1
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
34
Arrays
Array Addressing
The row number is always listed first
The colon operator selects individual elements, rows, columns,
or subarrays of arrays
v( : ) represents all the row or column elements of the vector v.
v(2 : 5) represents the second through fifth elements
A( : , 3) denotes all the elements in the third column of the matrix A
C = B(2:3, 1:3)
(
=
9 4 8
7 3 16
C
(
(
(
(
=
17 15 12 3
25 9 4 8
18 7 3 16
13 10 4 2
B
The general indexes of
two dimensional array
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
35
Arrays
The empty or null array
contains no elements, [ ]
Rows and columns can be deleted by setting the selected row or
column equal to the null array.
A(3, :) = [ ] deletes the third row in A
A(:, 2:4) = [ ] deletes the second through fourth columns In A
A([1 4], : ) = [ ] deletes the first and fourth rows of A
< Other examples >
(
=
7 5 1
4 9 6
A
A(1,5) = 3
(
=
0 0 7 5 1
3 0 4 9 6
A
B = A(:,5:1:1)
(
=
1 5 7 0 0
6 9 4 0 3
B
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
36
Arrays
Some Useful Array Functions
Command Description
cat(n, A, B, C, ) Creates a new array by concatenating the arrays A, B, C, and so on along the dimension n.
find(x) Computes an array containing the indices of the nonzero elements of the aray x.
[u, v, w] = find(A) Computes the arrays u and v, containing the row and column indices of the nonzero elements of the
matrix A, and the array w, containing the values of the nonzero elements. The array w may be omitted.
length(A) Computes either the number of elements of A if A is a vector or the largest value of m or n if A is an m
n matrix.
linspace(a,b,n) Creates a row vector of n regularly spaced values between a and b
logspace(a,b,n) Creates a row vector of n logarithmically spaced values between a and b
max(A) Returns the algebraically largest element in A if A is a vector. Returns a row vector containing the
largest elements in each column if A is a matrix. If any of the elements are complex, max(A) returns the
elements that have the largest magnitudes.
[x, k] = max(A) Similar to max(A) but stores the maximum values in the row vector x and their indices in the row vector
k
min(A) Same as max(A) but returns minimum values.
[x, k] = min(A) Same as [x, k] =max(A) but returns minimum values.
size(A) Returns a row vector [m n] containing the sizes of the m n array A.
sort(A) Sorts each column of the array A in ascending order and returns an array the same size as A.
sum(A) Sums the elements in each column of the array A and returns a row vector containing the sums.
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
37
Arrays
Magnitude, Length, and Absolute Value of a Vector
length : the number of elements in the vector.
magnitude :
absolute value : The absolute value of a vector x is a vector whose elements are the
absolute values of the elements of x.
<example>
x = [2, 4, 5]
length = 3, magnitude = 6.7082, absolute value = [2, 4, 5]
The Array Editor
A graphical interface for working with arrays.
To open the Array Editor from the Workspace Browser, doubleclick on the variable you
want to open.
2 2
2
2
1 n
x x x + + +
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
38
Multidimensional Arrays
MATLAB supports multidimensional arrays
The first two dimensions are the row and column, as with a matrix.
The higher dimensions are called pages.
<example>
Want to create a three dimensional array whose first page is
and whose second page is
>>A = [4, 6, 1;5, 8, 0;3, 9, 2];
>>A( : , : , 2) = [6, 2, 9;0, 3, 1;4, 7, 5];
(
(
(
2 9 3
0 8 5
1 6 4
(
(
(
5 7 4
1 3 0
9 2 6
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Multidimensional Arrays
cat command
(
=
5 9
2 8
A
(
=
3 7
6 4
B
C = cat(3, A, B) produces a threedimensional
array
<example>
>> A = [1 2;3 4];
>> B = [5 6;7 8];
>> C = cat(3, A, B) % concatenating the arrays A, B along the dimension three.
C(:,:,1) =
1 2
3 4
C(:,:,2) =
5 6
7 8
>> d = size(c)
d =
2 2 2
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
40
ElementbyElement Operations
Elementbyelement operations
Symbol Operation Form Example
+ Scalararray addition A + b [6, 3] + 2 = [8 ,5]
 Scalararray subtraction A b [8, 3]  5 = [3, 2]
+ Array addition A + B [6, 5] + [4, 8] = [10, 13]
 Array subtraction A B [6, 5]  [4, 8] = [2, 3]
.* Array multiplication A.*B [3, 5] .* [4, 8] = [12, 40]
./ Array right division A./B [2, 5] ./ [4, 8] = [2/4, 5/8]
.\ Array left division A.\B [2, 5] .\ [4, 8] = [2\4, 5\8]
.^ Array exponentiation A.^B [3, 5] .^2 = [3^2, 5^2]
2 .^ [3, 5] = [2^3, 2^5]
[3, 5] .^ [2, 4] = [3^2, 5^4]
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
ElementbyElement Operations
<example1>
<example2>
>> x = [ 1 2 3];
>> y = [ 4 5 6];
>> x.^y
ans=
1 32 729
>>y.^2
ans=
16 25 36
>>2.^[x y]
ans=
2 4 8 16 32 64
cf) ==> 2^[1 2 3 4 5 6] = [ 2^1 2^2 2^3 2^4 2^5 2^6 ]
>>x = 0:0.01:5
>>y = sin(x^2);
??? Error using ==> ^
Matrix must be square.
>>y=sin(x.^2);
>>plot(x,y);
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
42
Matrix Operations
Matrix Multiplication
Use the operator * to perform matrix multiplication in MATLAB
<example>
>>A = [6, 2,;10,3;4,7];
>>B = [9,8;5,12];
>>A*B
ans =
64 24
75 116
1 116
Special Matrices
Command Description
eye(n) Creates an nn identity matrix.
eye(size(A)) Creates an identity matrix the same size as the matrix A.
ones(n) Creates an nn matrix of ones.
ones(m,n) Creates an mn array of ones.
ones(size(A)) Creates an array of ones the same size as the array A.
zeros(n) Creates an nn matrix of zeros.
zeros(m,n) Creates an mn array of zeros.
zeros(size(A)) Creates an array of zeros the same size as the array A.
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
43
Matrix Operations
Matrix Division
Right and left operators, / and \
Chapter 6 covers matrix division and matrix inverse.
Matrix Exponentiation
must be a square matrix
to find A
2,
type A^2
Special products
Command Syntax
cross(A, B) Computes a 3n array whose columns are the cross
products of the corresponding columns in the 3n
arrays A and B. Returns a threeelement cross
product vector if A and B are threeelement vectors.
dot(A, B) Computes a row vector of length n whose elements
are the dot products of the corresponding columns
of the mn arrays A and B
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
44
Polynomial Operations Using Arrays
Type help polyfun for more information
We will use following notation
Polynomial Addition and Subtrction
add the arrays that describe their coefficients
if the polynomials are of different degrees, add zeros to the coefficient array of the
leowerdegree polynomial.
<example>
coefficient array is f=[9, 5, 3, 7] and g = [6, 1, 2]
g = [0 g] = [0, 6, 1, 2]
h = f+g = [9, 1, 2, 9]
1
2
1
2
3
1
2 1
) (
+
+ + + + + + =
n n n
n n n
a x a x a x a x a x a x f
7 3 5 9 ) (
2 3
+ + = x x x x f 2 6 ) (
2
+ = x x x g
) ( ) ( ) ( x g x f x h + =
9 2 9 ) (
2 3
+ + + = x x x x h
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
45
Polynomial Operations Using Arrays
Polynomial Multiplication and Division
Multiply polynomials : use conv function (it stands for convolve)
synthetic division : use deconv function (it stands for deconvolve)
Polynomial functions
Command Description
conv(a, b) Computes the product of the two polynomials described by the coefficient arrays a and b.
[q, r] = deconv(num,
den)
Computes the result of dividing a numerator polynomial, whose coefficient array is num, by a
denominator polynomial represented by the coefficient array den. The quotient polynomial is
given by the coefficient array q, and the remainder polynomial is given by the coefficient array
r.
poly(r) Computes the coefficients of the polynimial whose roots are specfied by the vector r.
polyval(a, x) Evaluates a polynomial at specified values of its independent variable x, which can be a matrix
or a vector. The polynomials coefficients of descending powers are stored in the array a. The
result is the same size as x.
roots(a) Computes the roots of a polynomial specified by the coefficient array a. The result is a column
vector that contains the polynomials roots.
14 29 41 39 54
) 2 6 )( 7 3 5 9 ( ) ( ) (
2 3 4 5
2 2 3
+ + + =
+ + + =
x x x x x
x x x x x x g x f
5833 . 0 5 . 1
2 6
7 3 5 9
) (
) (
2
2 3
=
+
+ +
= x
x x
x x x
x g
x f
>>f = [9, 5, 3, 7];
>>g = [6, 1, 2];
>>product = conv(f, g)
product =
54 39 41 29 1 14
>>quotient, remainder] = deconv(f,g)
quotient =
1.5 0.5833
remainder =
0 0 0.5833 8.1667
Acsl, Postech
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
46
Polynomial Operations Using Arrays
Plotting Polynomials
The polyval(a,x) function is very useful for poltting polynomials.
<example>
plot the polynomial
7 3 5 9 ) (
2 3
+ + = x x x x f 5 2 s s x for
2 1 0 1 2 3 4 5
200
0
200
400
600
800
1000
1200
x
f
(
x
)
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
47
Cell Arrays
Cell array : an array in which each element is a bin, or cell which can contain
an array.
examples
B = { [2, 4], [6,9;3, 5]; [7;2], 10 };
H = { [2, 4, 8], [6, 8, 3]; [2:6], [9, 2, 5]; [1, 4, 5], [7, 5, 2] };
J = [ H{1, 1}; H{1, 2}; H(2, 2} ];
10
5 3
9 6
(
  4 2
  2 7
(
(
(
=
5 2 9
3 8 6
8 4 2
J
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
48
Cell Arrays
Cell array functions
Function Description
C = cell(n) Creates an nn cell array C of empty matrices.
C = cell(n,m) Creates an nm cell array C of empty matrices.
celldisp(C) Display the contents of cell array C.
cellplot(C) Displays a graphical representation of the cell array C.
c = num2cell(A) Converts a numeric array A into a cell array C.
[X, Y, ] = deal(A,B, ) Matches up the input and output lists. Equivalent to X = A, Y = B,
[X, Y, ] = deal(A) Matches up the input and output lists. Equivalent to X = A, Y = A,
iscell(C) Returns a 1 if C is a cell array; otherwise, returns a 0.
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
49
Cell Arrays
Cell Array Function Examples
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
50
Structure Arrays
Structure arrays : composed of structures.
enables you to store dissimilar arrays together
accessed using namefields
Creating Structures
using assignment statements
using the struct function
dot notation (.) : to specify and to access the fields
<example>
student.name = John Smith;
student.SSN = 392771786;
student.email = smithj@myschool.edu;
student.tests = [67, 75, 84];
student(2).name = Mary Jones;
student(2).SSN = 431569832;
student(2).email = jonsm@myschool.edu;
student(2).tests = [84, 78, 93];
Structure array student
Student(1)
Name: John Smith
SSN: 392771786
Email: smithj@myschol.edu
Tests: 67, 75, 84
Student(2)
Name: Mary Jones
SSN: 431569832
Email: jonesm@myschol.edu
Tests: 84, 78, 93
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
51
Structure Arrays
Structure functions
Function Description
names = fieldnames(S) Returns the field names associated with the structure array S as
names, a cell array of strings
F = getfield(S, field) Returns the contents of the field field in the structure array S.
Equivalent to F = S.field
isfield(S, field) Returns 1 if field is the name of a field in the structure array S, and
0 otherwise
isstruct(S) Returns 1 if the array S is a structure array, and 0 otherwise
S = rmfield(S, field) Removes the field field from the structure array S.
S = setfield(S, field, V) Sets the contents of the field field to the value V in the structure
array S
S = struct(f1, v1, f2, v2, ) Creates a structure array with the fields f1, f2, having the
values v1, v2, .
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
52
Structure Arrays
Structure Arrays Examples
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
MATLAB
CHAPTER 3
Functions and Files
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Elementary Mathematical Functions
lookfor : find functions that are relevant to your
application
help : when you know the correct spelling of the function
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Exponential and Logarithmic Functions
Some common
mathematical
functions
Exponential
exp(x) Exponential;
sqrt(x) Square root;
Logarithmic
log(x) Natural logarithm; ln x
log10(x) Common(base10)
logarithm;
log(x) means ln x.
x
e
x
Complex
abs(x) Absolute value; x
angle(x) Angle of a complex number x
conj(x) Complex conjugate
imag(x) Imaginary part of a complex
number x
real(x) Real part of a complex number x
Numeric
ceil(x) Round to the nearest integer
toward
fix(x) Round to the nearest integer
toward zero.
floor(x) Round to the nearest integer
toward
round(x) Round toward nearest integer
sign(x) Signum function:
+1 if x> 0; if x = 0; 1 if x < 0
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Complex Number Functions(1/2)
rectangular representation
a + ib
polar representation
abs(x), angle(x)
absolute value (magnitude)
angle
conj(x)
complex conjugate
MZ
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Complex Number Functions(2/2)
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Numeric Functions
MATLAB has been optimized to deal with arrays.
round(y) : rounds to the nearest integer ans = 2, 3, 4
fix(y) : truncates to the nearest integer toward zero ans = 2, 2, 3
ceil(y) : rounds to the nearest integer toward ans = 3, 3, 4
e.g. z = [2.6 , 2.3 , 5.7]
floor(z) : rounds to the nearest integer toward  ans = 3, 3, 5
fix(z) = 2, 2, 5
abs(z) = 2.6 , 2.3, 5.7
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Trigonometric Functions
Table 3.12
Trigonometric functions
Trigonometric
*angle : radian
cos(x) Cosine; cos x.
cot(x) Cotangent; cot x.
csc(x) Cosecant; csc x.
sec(x) Secant; sec x.
sin(x) Sine; sin x.
tan(x) Tangent; tan x.
Inverse
trigonometric
acos(x) Inverse cosine;
arccos x =
acot(x) Inverse cotangent;
arccot x =
acsc(x) Inverse cosecant;
arccsc x =
asec(x) Inverse secant;
arcsec x =
asin(x) Inverse sine;
arcsin x =
atan(x) Inverse tangent;
arctan x =
atan2(y,x) fourquadrant
inverse tangent.
x cos
1
x cot
1
x csc
1
x sec
1
x sin
1
x t an
1
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Hyperbolic Functions(1/2)
Hyperbolic
functions
Hyperbolic
cosh(x) Hyperbolic cosine; cosh x =
coth(x) Hyperbolic cotangent; cosh x / sinh x
csch(x) Hyperbolic cosecant; 1 / sinh x
sech(x) Hyperbolic secant; 1 / cosh x
sinh(x) Hyperbolic sine; sinh x =
tanh(x) Hyperbolic tangent; sinh x / cosh x
)/ 2 e (e
x x
+
)/ 2 e (e
x x
1
2
1
< >
+
=
x 1 x ),
1  x
1 x
ln( x coth or
1
0 x ), 1
x
1
x
1
l n( x csch
2
1
= + + =
1 x 0 ), 1
x
1
x
1
l n( x sech
2
1
s < + =
< < + + =
x  ), 1 x ln(x x sinh
2 1
1 x 1 ),
x  1
x 1
ln(
2
1
x tanh
1
< <
+
=
= u
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Program design and development(3/3)
Example 3. iterative operations
Determine how many terms are
required for the sum of the series
10k
2
4k+2 , k=1,2,3, to exceed
20,000
Total =0;
K =0;
While total <2e+4
k =k+1;
Total =10*k^2 4*k +2 +total;
end
disp ( The number of terms is : )
disp ( k )
disp ( The sum is : )
disp ( total )
Total > 20,000 ?
Total = 0
k = 0
Total =10k
2
4k+2
k = k + 1
START
END
DISP k, Total
True
False
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Relational operators and logical variables(1/2)
Table 4.21 Relational operators
Relational
operator
Meaning
< Less than
<= Less than or equal
to
> Greater than
>= Greater than or
equal to
==
Equal to
~= Not equal to
Example
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Relational operators and logical variables(2/2)
The logical class
example
The logical function
example
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Logical operators and functions(1/6)
Table 4.31 logical operators
Operator Name Definition
~ NOT ~A returns an array the same dimension as A; the new
array has ones where A is zero and zeros where A is
nonzero.
& AND A&B returns an array the same dimension as A and B;
the new array has ones where both A and B have
nonzero elements and zeros where either A or B is zero.
 OR AB returns an array the same dimension as A and B; the
new array has ones where at least one element in A or B
is nonzero and zeros where A and B are both zero.
&& ShortCircuit
AND
Operator for scalar logical expressions. A && B returns
true if both A and B evaluate to true, and false if they do
not.
 ShortCircuit
OR
Operator for scalar logical expressions. A  B returns
true if either A or B or both evaluate to true, and false if
they do not.
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Logical operators and functions(2/6)
Example
1. Not
2. And
3. Or
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Logical operators and functions(3/6)
Table 4.32 order of precedence for operator types
Precedence Operator type
First Parentheses () ; evaluated starting with the
innermost pair.
Second Arithmetic operators and logical NOT(~); evaluated
from left to right.
Third Relational operators ; evaluated from left to right
Fourth Logical AND.
Fifth Logical OR.
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Logical operators and functions(4/6)
x y ~x xy x&y xor(x,y)
True True False True True False
True False False True False True
False True True True False True
False False True False False False
Table 4.33 Truth table
example
Shortcircuit operators
A && B Returns true (logical 1) if both A and B evaluate to true, and false (logical 0) if they do
not.
A   B Returns true (logical 1) if either A or B, or both, evaluate to true, and false (logical 0) if
they do not.
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Logical operators and functions(5/6)
Table 4.34 logical functions
Logical function Definition
all(x)
Returns a scalar, which is 1 if all the elements in the vector x are nonzero and 0 otherwise.
all(A)
Returns a row vector having the same number of columns as the matrix A and containing ones and zeros,
depending on whether or not the corresponding column of A has all nonzero elements.
any(x)
Returns a scalar, which is 1 if any of the elements in the vector x is nonzero and 0 otherwise.
any(A)
Returns a row vector having the same number of columns as A and containing ones and zeros, depending on
whether or not the corresponding column of the matrix A contains any nonzero elements.
find(A)
Computes an array containing the indices of the nonzero elements of the array A.
[u,v,w]=find(A)
Computes the arrays u and v containing the row and column indices of the nonzero elements of the array A
and computes the array w containing the values of the nonzero elements. The array w may be omitted.
finite(A)
Returns an array of the same dimension as A with ones where the elements of A are finite and zeros
elsewhere.
ischar(A)
Returns a 1 if A is a character array and 0 otherwise.
isempty(A)
Returns a 1 if A is an empty matrix and 0 otherwise.
isinf(A)
Returns an array of the same dimension as A, with ones where A has inf and zeros elsewhere.
isnan(A)
Returns an array of the same dimension as A with ones where A has NaN and zeros elsewhere. (NaN
stands for not a munber, which means an undefined result.)
isnumeric(A)
Returns a 1 if A is a numeric array and 0 otherwise.
isreal(A)
Returns a 1 if A has no elements with imaginary parts and 0 otherwise.
logical(A)
Converts the elements of the array A into logical values.
xor(A,B)
Returns an array the same dimension as A and B; the new array has ones where either A or B is nonzero, but
not both, and zeros where A and B are either both nonzero or both zero.
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Logical operators and functions(6/6)
Logical operators and the find function
Find(x): computes an array containing the indices of the nonzero elements of the array x.
example
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Conditional statements(1/5)
the if statement
The if statements basic form is
if logical expression
statements
end
the nested if statement
if logical expression 1
statements group 1
if logical expression 2
statement group 2
end
end
Start
Logical
Expression 1
Statement
Group 1
True
False
False
Logical
Expression 2
Statement
Group 2
Statement
Group 3
True
End
Figure 4.43 flowchart for
the general if structure
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Conditional statements(2/5)
Example
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Conditional statements(3/5)
the else statement
if logical expression
statements group 1
else
statements group 2
end
example
Start
Statement
Group2
Statement
Group1
Logical
Expression
False
End
True
Figure 4.42 flowchart for
the general else structure
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Conditional statements(4/5)
the elseif statement
if logical expression
statements group 1
elseif logical
expression2
statements group 2
else
statements group 3
end
Checking the number of input and
output arguments
narginnumber of input arguments
Function z=sqrtfun(x,y)
if(nargin==1)
z=sqrt(x);
elseif(nargin==2)
z=sqrt((x+y)/2);
end
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Conditional statements(5/5)
Strings and conditional statements
Name
Number
findstr
Input
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Loops (1/4)
for Loops
for loop variable=m:s:n
statements
end
Example
for k=5:10:35
x=k^2
end
Figure 4.51 flowchart
of a for loop.
Start
Set k = m
Increment
k by s
k > n ?
False
End
True
Statements
Statements
following the
End statement
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Loops (2/4)
break terminates the loop
but does not stop the entire
program
example
for k=1:10
x=50k^2;
if x<0
break
end
y=sqrt(x)
end
Continuepasses control to the
next iteration of the for or while
loop in which it appears
example
x=[10,1000,10,100];
y=NaN*x;
for k=1:length(x)
if x(k)<0
continue
end
y(k)=log10(x(k));
end
y
The result is y=1,3,NaN,2.
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Loops (3/4)
Using an array as a loop index
example
A=[1,2,3;4,5,6];
for v=A
disp(v)
end
Implied Loops
Use of logical arrays as masks
example
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
Loops (4/4)
while Loops
while loop variable=m:s:n
statements
End
Example
x=5;
while x<25
disp(x)
x=2*x1;
end
1. The loop variable must have a value
before the while statement is executed.
2. The loop variable must be changed
somehow by the statements.
Figure 4.53 flowchart
of the while loop.
Statements
following the
End statement
End
Start
Logical
Expression
True
False
Statements
(which increment
the loop variable)
MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays
The switch structure
switch input expression (scalar
or string)
case value 1
statement group 1
case value 2
statement group 2
.
.
.
Otherwise
statement group n
end
example
switch angle
case 45
disp(Northeast)
case 135
disp(Southeast)
case 225
disp(Southwest)
case 315
disp(Northwest)
otherwise
disp(Direction Unknown)
end
107
MATLAB
CHAPTER 5
Advanced Plotting and Model Building
MATLAB : Chapter 5. Advanced Plotting and Model Building
108
xy Plotting Functions
0 1 2 3 4 5 6 7 8 9 10
0
200
400
600
800
1000
1200
1400
1600
Time (seconds)
H
e
i
g
h
t
(
f
e
e
t
)
Height of a Falling Object Versus Time
Zero Drag Model
Data
LEGEND
TICK MARK
TICKMARK LABEL
AXIS LABEL
DATA SYMBOL
PLOT TITLE
The Anatomy of a Plot
SPaC, Postech
MATLAB : Chapter 5. Advanced Plotting and Model Building
109
xy Plotting Functions
Requirements for a Correct Plot
1. Each axis must be labeled with the name of the quantity being plotted and its
units.
2. Each axis should have regularly spaced tick marks at convenient intervals with a
spacing that is easy to interpret and interpolate.
3. If you are plotting more than one curve or data set, label each on its plot or use a
legend to distinguish them.
4. If you are preparing multiple plots of similar type or if the axes labels cannot
convey enough information, use a title.
5. If you are plotting measured data, plot each data point with a symbol.
6. Sometimes data symbols are connected by lines to help the viewer visualize the
data. You should be careful to prevent the misinterpretation when connecting the
data points, especially with a solid line.
7. If you are plotting points generated by evaluating a function, do not use a symbol
to plot the points. Instead, be sure to generate many points, and connect the
points with solid lines.
MATLAB : Chapter 5. Advanced Plotting and Model Building
110
xy Plotting Functions
Plot, Label, and Title Commands
xlabel and ylabel commands put labels
on the abscissa and the ordinate.
title command puts a title at the top of the
plot.
<example>
>>x = [0:0.1:52] ;
>>y = 0.4*sqrt(1.8*x) ;
>>plot (x,y)
>>xlabel ( Distance (miles) )
>>ylabel ( Height (miles) )
>>title ( Rocket Height as a Function of
Downrange Distance )
0 10 20 30 40 50 60
0
0.5
1
1.5
2
2.5
3
3.5
4
Distance (miles)
H
e
i
g
h
t
(
m
i
l
e
s
)
Rocket Height as a Function of Downrange Distance
SPaC, Postech
MATLAB : Chapter 5. Advanced Plotting and Model Building
111
xy Plotting Functions
grid and axis Commands
grid: displays gridlines at the tick marks corresponding to the tick labels.
axis: override the MATLAB selections for the axis limits.
Basic syntax: axis ( [xmin xmax ymin ymax] )
SPaC, Postech
MATLAB : Chapter 5. Advanced Plotting and Model Building
112
xy Plotting Functions
Plots of Complex Numbers
plot (y): Plots the imaginary parts of y versus the real parts if y is a vector having
complex values.
SPaC, Postech
MATLAB : Chapter 5. Advanced Plotting and Model Building
113
xy Plotting Functions
The Function Plot Command fplot
fplot: automatically analyzes the function to be plotted and decides
how many plotting points to use so that the plot will show all the
features of the function.
Basic syntax: fplot ( string , [xmin xmax] )
where string is a text string that describes the function to be plotted
and [xmin xmax] specifies the minimum and maximum values of
the independent variable.
SPaC, Postech
MATLAB : Chapter 5. Advanced Plotting and Model Building
114
xy Plotting Functions
Plotting Polynomials
We can plot polynomials more easily by using the polyval function
<example>
Plot the polynomial
>>x = [6:0.01:6];
>>p = [3,2,100,2,7,90];
>>plot (x, polyval (p,x)), xlabel (x), ylabel (p)
) (x f
6 4 2 0 2 4 6
3000
2000
1000
0
1000
2000
3000
4000
5000
90 7 2 100 2 3 ) (
2 3 4 5
+ + + = x x x x x x f
) 6 6 ( s s x
SPaC, Postech
MATLAB : Chapter 5. Advanced Plotting and Model Building
115
Subplots and Overlay Plots
Basic xy plotting commands
Command Description
axis([xmin, xmax ymin
ymax])
fplot(string, [xmin xmax])
Grid
plot(x,y)
plot(y)
print
title (text)
xlabel (text)
ylabel (text)
Sets the minimum and maximum limits of the x and yaxes.
Performs intelligent plotting of functions, where string is a
text string that described the function to be plotted and
[xmin xmax] specifies the minimum and maximum values
of the independent variable. The range of the dependent
variable can also be specified. In this case the syntax is
fplot(string, [xmin xmax ymin ymax]).
Display gridlines at the tick marks corresponding to the
tick labels.
Generates a plot of the array y versus the array x on
rectilinear axes.
Plots the values of y versus their indices if y is a vector.
Plots the imaginary parts of y versus the real parts if y is a
vector having complex values.
Prints the plot in the Figure window.
Puts text in a title at the top of a plot.
Adds a text label to the xaxis(the abscissa).
Adds a text label to the yaxis(the ordinate).
MATLAB : Chapter 5. Advanced Plotting and Model Building
116
Subplots and Overlay Plots
Subplots
Basic syntax: subplot (m, n, p)
<example1>
subplot (3, 2, 5) : This command creates an array of six pane, three panes deep and two
panes across, and directs the next plot to appear in the fifth pane (in the bottomleft corner).
<example2>
X = [0:0.01:5];
y = exp(1.2*x).*sin(10*x+5);
subplot(1,2,1)
plot(x,y),xlabel('x'),ylabel('y'),
axis([0 5 1 1])
x = [6:0.01:6];
y = abs(x.^3100);
subplot(1,2,2)
plot(x,y),xlabel('x'),ylabel('y'),
axis([6 6 0 350])
MATLAB : Chapter 5. Advanced Plotting and Model Building
117
Subplots and Overlay Plots
Overlay plots
Need to plot more than one curve or data set on a single plot.
Data Markers and Line Types
Data markers Line types Colors
Dot (.) .
Asterisk (*) *
Cross (x) x
Circle (o) o
Plus sign (+) +
Square () s
Diamond () d
Fivepointed star () p
Solid line 
Dashed line  
Dashdotted line .
Dotted line :
Black k
Blue b
Cyan c
Green g
Magenta m
Red r
White w
Yellow y
SPaC, Postech
MATLAB : Chapter 5. Advanced Plotting and Model Building
118
Subplots and Overlay Plots
Data Markers and Line Types
plot(x,y,'*',x,y,':)
plot(x,y,x,y,'o)
plot(x,y,'o)
SPaC, Postech
MATLAB : Chapter 5. Advanced Plotting and Model Building
119
Subplots and Overlay Plots
Labeling Curves and Data
legend command: legend (string1, string2)
where string1 and string2 are text strings of your choice.
gtext command: gtext (string) add a text string to the plot.
text command: text (x, y, string)
SPaC, Postech
MATLAB : Chapter 5. Advanced Plotting and Model Building
120
Subplots and Overlay Plots
The hold Command
hold command create a plot that needs two or more plot
commands.
be useful with some of the advanced MATLAB toolbox
commands that generate specialized plots.
<example>
1 0 1 2 3 4 5 6
1
0
1
2
3
4
5
6
7
y2 versus y1
Imag(z) versus Real(z)
SPaC, Postech
MATLAB : Chapter 5. Advanced Plotting and Model Building
121
Subplots and Overlay Plots
Plot enhancement commands
Command Description
axes
gtext (text)
hold
legend (leg1, leg2, )
plot (x, y, u, v)
plot (x, y, type)
plot (A)
plot (P, Q)
refresh
subplot (m, n, p)
text (x, y, text)
Creates axes objects.
Places the string text in the Figure window at a point specified by the mouse.
Freezes the current plot for subsequent graphics commands.
Creates a legend using the strings leg1, leg2, and so on and specifies its
placement with the mouse.
Plots, on rectilinear axes, four arrays: y versus x and v versus u.
Plots the array y versus the array x on rectilinear axes, using the line type,
data marker, and colors specified in the string type.
Plots the columns of the m n array A versus their indices and generates n
curves.
Plots array Q versus array P. See the text for a description of the possible
variants involving vectors and/or matrices: plot (x, A), plot (A, x), and plot (A,
B).
Redraws the current Figure window.
Splits the Figure window into an array of subwindows with m rows and n
columns and directs the subsequent plotting commands to the pth
subwindow.
Places the string text in the Figure window at a point specified by
coordinates x, y.
MATLAB : Chapter 5. Advanced Plotting and Model Building
122
Subplots and Overlay Plots
Annotating Plots
\ tau & \ omega represent the Greek letters and .
^ : superscript, _ : subscript.
<example>
X_{13} x
13
Hints for Improving Plots
1. Start scales from zero whenever possible.
2. Use sensible tickmark spacing.
3. Minimize the number of zeros in the data being plotted.
4. Determine the minimum and maximum data values for each axis before
plotting the data.
5. Use a different line type for each curve when several are plotted on a single
plot and they cross each other
6. Do not put many curves on one plot, particularly if they will be close to each
other or cross one another at several points.
7. Use the same scale limits and tick spacing on each plot if you need to
compare information on more than one plot.
MATLAB : Chapter 5. Advanced Plotting and Model Building
123
Special Plot Types
Logarithmic plots
loglog plot: log scales on both axes.
semilog plot: a log scale on only one axis.
MATLAB : Chapter 5. Advanced Plotting and Model Building
124
Special Plot Types
Specialized plot commands
Command Description
bar (x, y)
loglog (x, y)
plotyy (x1, y1, x2, y2)
polar (theta, r, type)
semilogx (x, y)
semilogy (x, y)
stairs (x, y)
stem (x, y)
Creates a bar chart of y versus x.
Produces a loglog plot of y versus x.
Produces a plot with two yaxes, y1 on the left and y2 on
the right.
Produces a polar plot from the polar coordinates theta
and r, using the line type, data marker, and colors
specified in the string type.
Produces a semilog plot of y versus x with logarithmic
abscissa scale.
Produces a semilog plot of x versus y with logarithmic
abscissa scale.
Produces a stairs plot of y versus x.
Produces a stem plot of y versus x.
SPaC, Postech
MATLAB : Chapter 5. Advanced Plotting and Model Building
125
Special Plot Types
FrequencyResponse Plots and Filter Circuits
<example> FrequencyResponse Plot of a LowPass Filter
, where s = i and RC = 0.1 second
1
1
+
=
RCs A
A
i
o
R
C
+

vi vo
10
0
10
1
10
2
10
1
10
0
Frequency (rad/s)
O
u
t
p
u
t
/
I
n
p
u
t
R
a
t
i
o
Frequency Response of a LowPass RC Circuit (RC = 0.1 s)
MATLAB : Chapter 5. Advanced Plotting and Model Building
126
ThreeDimensional Plots
Example
[X, Y] = meshgrid(2:0.1:2);
Z = X.*exp(((XY.^2).^2+Y.^2));
mesh(X,Y,Z) meshc(X,Y,Z) surf(X,Y,Z)
surfc(X,Y,Z) meshz(X,Y,Z) waterfall(X,Y,Z)
MATLAB
CHAPTER 6
Numerical calculus and differential equations
MATLAB : Chapter 8. Numerical calculus and differential equations
OUTLINE
Numerical integrationI(2)
Numerical differentiation(3)
Numerical Methods for Differential Equations(7)
Extension to HigherOrder Equations(6)
ODE Solvers in the Control System Toolbox(7)
Advanced Solver Syntax(2)
MATLAB : Chapter 8. Numerical calculus and differential equations
Numerical integrationI(1/2)
Rectangular integration trapezoidal integration
Numerical integration functions
Command
Description
quad (function,a,b,tol)
Uses an adaptive Simpsons rule to compute the integral of the function
function with a as the lower integration limit and b as the upper limit. The
parameter tol is optional. tol indicates the specified error tolerance.
quadl (function, a,b,tol)
Uses Lobatto quadrature to compute the integral of the function function. The
rest of the syntax is identical to quad.
trapz (x,y)
Uses trapezoidal integration to compute the integral of y with respect to x,
where the array y contains the function values at the points contained in the
array x.
y
x a b
y=f(x)
y=f(x)
y
x a b
}
t
0
sin dx
2 cos 0 cos cos sin
0
0
= = =
}
t
t
t
x dx
(exact solution)
(use of the trapz
function)
MATLAB : Chapter 8. Numerical calculus and differential equations
Numerical integrationI(2/2)
Quadrature functions
quad (function,a,b)
quadl (function,a,b)
Slope function singularities
example
x dx dy
x y
/ 5 . 0 / =
=
(The slope has a singularity at x=0)
The answer is A1=A2=0.6667, A3=0.6665
Compared to Trapz, exactness
is high, but it is impossible to
integrate discretized data (only
possible for fixed to function)
MATLAB : Chapter 8. Numerical calculus and differential equations
Numerical differentiation(1/3)
x
y y
x x
y y
mB
A
=
2 3
2 3
2 3
x
1
x
2
x
3
y
1
y
2
y
3
x
x
y=f(x)
True slope
A
B
C
x
y y
x
y y
x
y y m m
m
B A
C
A
=

.

\

A
+
A
=
+
=
2 2
1
2
1 3 2 3 1 2
x
y y
x x
y y
mA
A
=
1 2
1 2
1 2
x
y
dx
dy
A
A
= lim x 0
: backward difference
: central difference
: forward difference
: Difinition
MATLAB : Chapter 8. Numerical calculus and differential equations
Numerical differentiation(2/3)
The diff Function
d= diff (x) >( d=[x(2)x(1),x(3)x(2), ] )
Backward difference & central
difference method
example :
example : x=[5, 7, 12, 20];
d= diff(x)
d = 2 5 32
MATLAB : Chapter 8. Numerical calculus and differential equations
Numerical differentiation(3/3)
b = polyder (p)
p = [a
1
,a
2
,,a
n
]
b = [b
1
,b
2
,,b
n1
]
b = polyder (p1,p2)
[num, den] = polyder(p2,p1)
n n
n n n
a x a x a x a x a x f + + + + + =
1
2
3
1
2 1 ) (
1
2
2
1
1 ) 1 (
+ + + = n
n n
a x a n x na
dx
df
1
2
2
1
1
+ + + = n
n n
b x b x b
Example p1= 5x +2
p2=10x
2
+4x3
Result: der2 = [10, 4, 3]
prod = [150, 80, 7]
num = [50, 40, 23]
den = [25, 20, 4]
Command Description
d=diff(x) Returns a vector d containing the differences between adjacent elements in the vector x.
b=polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented
by the vector p.
b=polyder(p1,p2) Returns a vector b containing the coefficients of the polynomial that is the derivative of the
product of the polynomials represented by p1 and p2. cf. equivalent comment:
b=polyder(conv(p1,p2))
[num, den]=
polyder(p2,p1)
Returns the vector num and den containing the coefficients of the numerator and denominator
polynomials of the derivative of the quotient p
2
/p
1
, where p1 and p2 are polynomials.
Numerical differentiation functions
polynomial Derivatives
MATLAB : Chapter 8. Numerical calculus and differential equations
Numerical Methods for Differential Equations(1/7)
RungeKutta Methods
The secondorder RungeKutta methods:
(8.517) , where : constant weighting factors
(8.518)
(8.519)
To duplicate the Taylor series through the h
2
term, these coefficients
must satisfy the following:
(8.519)
(8.519)
(8.519)
2 2 1 1 1
g w g w y y
k k
+ + =
+
) , (
) , (
2
1
k k k
k k
hf y h t hf g
y t hf g
 o + + =
=
2 1
, w w
2
1
2
1
1
2
1
2 1
=
=
= +

o
w
w
w w
MATLAB : Chapter 8. Numerical calculus and differential equations
Numerical Methods for Differential Equations(2/7)
The fourthorder RungeKutta methods:
(8.523)
(8.524)
4 4 3 3 2 2 1 1 1
g w g w g w g w y y
k k
+ + + + =
+
] ) ( , [
] ) ( , [
) , (
) , (
1 3 3 3 3 3 2 3 3 4
1 2 2 2 2 2 3
1 1 2
1
g g g y h t hf g
g g y h t hf g
g y h t hf g
y t hf g
k k
k k
k k
k k
 o  o
 o  o
o o
+ + + + =
+ + + =
+ + =
=
0
1
2 1
2 1
3 1
6 1
3
3 3
2
2 1
3 2
4 1
=
= =
=
= =
= =
= =

o

o o
w w
w w
MATLAB : Chapter 8. Numerical calculus and differential equations
Numerical Methods for Differential Equations(3/7)
MATLAB ODE Solvers ode23 and ode45
MATLAB provides functions, called solvers, that implement RungeKutta
methods with variable step size.
The ode23 function uses a combination of second and thirdorder Runge
Kutta methods, whereas ode45 uses a combination of fourth and fifthorder
methods.
<Table 8.51> ODE solvers
Solver name Description
ode23 Nonstiff, loworder solver.
ode45 Nonstiff, mediumorder solver.
ode113 Nonstiff, variableorder solver.
ode23s Stiff, loworder solver.
ode23t Moderately stiff, trapezoidalrule solver.
ode23tb Stiff, loworder solver.
ode15s Stiff, variableorder solver.
MATLAB : Chapter 8. Numerical calculus and differential equations
Numerical Methods for Differential Equations(4/7)
Solver Syntax
<Table 8.52> Basic syntax of ODE solvers
Command Description
[t, y] = ode23( ydot, tspan, y0) Solves the vector differential equation specified
in function file ydot, whose inputs must be t and y and
whose output must be a column vector representing
; that is, . The number of rows in this column
vector must equal the order of the equation. The vector
tspan contains the starting and ending values of the
independent variable t, and optionally, any intermediate
values of t where the solution is desired. The vector y0
contains. The function file must have two input
arguments t and y even for equations where is not
a function of t. The syntax is identical for the other
solvers.
) , (
.
y t f y =
dt dy
) , (
.
y t f y =
) (
0
t y
) , ( y t f
MATLAB : Chapter 8. Numerical calculus and differential equations
Numerical Methods for Differential Equations(5/7)
<example> Response of an RC Circuit
(RC=0.1s, v(0)=0V, y(0)=2V)
) (t v y
dt
dy
RC = +
R
c y
v

+
y y 10
.
=
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2
Time(s)
C
a
p
a
c
i
t
o
r
V
o
l
t
a
g
e
numerical solution
analytical solution
MATLAB : Chapter 8. Numerical calculus and differential equations
Numerical Methods for Differential Equations(6/7)
Effect of Step Size
The spacing used by ode23 is smaller than that used by ode45 because
ode45 has less truncation error than ode23 and thus can use a larger step
size.
ode23 is sometimes more useful for plotting the solution because it often
gives a smoother curve.
Numerical Methods and Linear Equations
It is sometimes more convenient to use a numerical method to find the
solution.
Examples of such situations are when the forcing function is a complicated
function or when the order of the differential equation is higher than two.
Use of Global Parameters
The global x y z command allows all functions and files using that command to share
the values of the variables x, y, and z.
MATLAB : Chapter 8. Numerical calculus and differential equations
Numerical Methods for Differential Equations(7/7)
Use of Global Parameters
( Example ) The circuits equation was given earlier. It is
Solving for the derivative and using RC=0.1, we obtain
( )
dy
RC y v t
dt
+ =
10[ ( ) ]
dy
v t y
dt
=
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
2
0
2
4
Time (s)
A
p
p
l
i
e
d
V
o
l
t
a
g
e
(
V
)
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
1
0
1
2
3
Time (s)
C
a
p
a
c
i
t
o
r
V
o
l
t
a
g
e
(
V
)
< Solution >
< Result >
MATLAB : Chapter 8. Numerical calculus and differential equations
Extension to HigherOrder Equations(1/6)
The Cauchy form or the statevariable form
Consider the secondorder equation
(8.61)
(8.62)
If , , then
5 7 4 ( ) y y y f t + + =
1 4 7
( )
5 5 5
y f t y y =
y x =
1
2
x y =
2 1
.
2
2
.
1
5
7
5
4
) (
5
1
x x t f x
x x
=
=
The Cauchy form
or statevariable form
MATLAB : Chapter 8. Numerical calculus and differential equations
Extension to HigherOrder Equations(2/6)
<example> Solve (8.61) for with the initial conditions .
( Suppose that and use ode45.)
6 0 s st 9 ) 0 ( , 3 ) 0 (
.
= = y y
) sin( ) ( t t f =
xdot(1)
xdot(2)
x(1)
x(2)
.
1
x
.
2
x
1
x
2
x
The initial condition for
the vector x.
0 1 2 3 4 5 6
4
2
0
2
4
6
8
10
MATLAB : Chapter 8. Numerical calculus and differential equations
Extension to HigherOrder Equations(3/6)
Matrix Methods
< a mass and spring with viscous surface friction >
y
f(t)
m
k
c
) (
. ..
t f ky y c y m = + +
2 1
.
x x =
2 1 2
) (
1
.
x
m
c
x
m
k
t f
m
x =
( Letting , )
y x =
1
.
2
y x =
) (
1
0 1 0
2
1
2
1
.
.
t f
m
x
x
m
c
m
k
x
x
(
(
+
(
(
(
=
(
(
(Matrix form)
) (
.
t f B + AX = X
(
(
= A
m
c
m
k
1 0
(
(
= B
m
1
0
(
= X
2
1
x
x
(Compact form)
(8.66)
(8.67)
MATLAB : Chapter 8. Numerical calculus and differential equations
Extension to HigherOrder Equations(4/6)
Characteristic Roots from the eig Function
Substituting ,
Cancel the terms
Its roots are s = 6.7321 and s = 3.2679.
2 1 1
3
.
x x x + =
2 1 2
7
.
x x x =
(8.68)
(8.68)
st st st
st st st
e A e A e sA
e A e A e sA
2 1 2
2 1 1
7
3
=
+ =
st
e A t x
1 1
) ( =
st
e A t x
2 2
) ( =
st
e
0 ) 7 (
0 ) 3 (
2 1
2 1
= + +
= +
A s A
A A s
0 22 10
7 1
1 3
2
= + + =
+
+
s s
s
s
A nonzero solution will exist for A1 and A2 if
and only if the determinant is zero
MATLAB : Chapter 8. Numerical calculus and differential equations
Extension to HigherOrder Equations(5/6)
MATLAB provides the eig function to compute the characteristic roots.
Its syntax is eig(A)
<example> The matrix A for the equations (8.68) and (8.69) is
To find the time constants, which are the negative reciprocals of the
real parts of the roots, you type tau = 1./real (r). The time constants
are 0.1485 and 0.3060.
(
7 1
1 3
MATLAB : Chapter 8. Numerical calculus and differential equations
Extension to HigherOrder Equations(6/6)
Programming Detailed Forcing Functions
< An armaturecontrolled dc motor>
v
R L
I
+

w K
e
i K T
T
=
w
cw
i
cw i K
dt
dw
I
t v w K Ri
dt
di
L
T
e
=
+ = ) (
) (
0
1
2
1
2
1
.
.
t v
L
x
x
I
c
I
K
L
K
L
R
x
x
T
e
(
(
+
(
(
(
(
=
(
(
= X
(
(
= B
(
(
= A
B + AX = X
2
1
2
1
0
2
3
2
5
1 0
.
x
x
u
(8.75)
(8.73)
(8.74)
(8.72)
Both model forms contain the same
information. However, each form
has its own advantages, depending
on the purpose of the analysis.
The specification of the
output:
Du C y + X =
MATLAB : Chapter 8. Numerical calculus and differential equations
ODE Solvers in the Control System Toolbox(2/7)
< Table 8.71> LTI object functions
Command Description
sys = ss (A, B, C, D) Creates an LTI object in statespace form, where the
matrices A, B, C, and D correspond to those in the
model .
[A, B, C, D] = ssdata (sys) Extracts the matrices A, B, C, and D corresponding to
those in the model
.
sys = tf (right, left) Creates an LTI object in transferfunction form, where
the vector right is the vector of coefficients of the right
hand side of the equation, arranged in descending
derivative order, and left is the vector of coefficients of
the lefthand side of the equation, also arranged in
descending derivative order.
[right, left] = tfdata (sys) Extracts the coefficients on the right and lefthand
sides of the reducedform model.
Du C y u + X = B + AX = X ,
.
Du C y u + X = B + AX = X ,
.
MATLAB : Chapter 8. Numerical calculus and differential equations
ODE Solvers in the Control System Toolbox(3/7)
Example
MATLAB : Chapter 8. Numerical calculus and differential equations
ODE Solvers in the Control System Toolbox(4/7)
ODE Solvers
<Table 8.72> Basic syntax of the LTI ODE solvers
LTI Viewers: It provides an interactive user interface that allows you to
switch between different types of response plots and between the analysis
of different systems. The viewer is invoked by typing ltiview.
Command Description
Impulse (sys) Computes and plots the unitimpulse response of the LTI
object sys.
Initial (sys, x0) Computes and plots the free response of the LTI object sys
given in statemodel form, for the initial conditions specified in
the vector x0.
lsim (sys, u, t) Computes and plots the response of the LTI object sys to the
input specified by the vector u, at the times specified by the
vector t.
step (sys) Computes and plots the unitstep response of the LTI object
sys.
MATLAB : Chapter 8. Numerical calculus and differential equations
ODE Solvers in the Control System
Toolbox(5/7)
Example
>> initial(sys2,[5,2])
0 1 2 3 4 5 6 7 8
1
0
1
2
3
4
5
6
Response to Initial Conditions
Time (sec)
A
m
p
l i t
u
d
e
>> Impulse(sys2)
0 1 2 3 4 5 6 7 8
0.05
0
0.05
0.1
0.15
0.2
Impulse Response
Time (sec)
A
m
p
l i t
u
d
e
0 1 2 3 4 5 6 7 8
0
0.05
0.1
0.15
0.2
0.25
Step Response
Time (sec)
A
m
p
l i t
u
d
e
>> step(sys2)
MATLAB : Chapter 8. Numerical calculus and differential equations
ODE Solvers in the Control System Toolbox(6/7)
Predefined Input Functions
< Table 8.73 > Predefined input functions
Command Description
[u, t] = gensig
(type, period, tf, dt)
Generates a periodic input of a specified type, having a period. The
following types are available: sine wave (type = sin), square wave (type
= square), and narrowwidth periodic pulse (type = pulse). The vector t
contains the times, and the vector u contains the input values at those
times. All generated inputs have unit amplitudes. The optional
parameters tf and dt specify the time duration tf of the input and the
spacing dt between the time instants.
sawtooth (t, width) Returns a vector the same length as t corresponding to a sawtooth wave
of period 2. The optional parameter width generates a modified
sawtooth wave where width determines the fraction between 0 and 2
at which the maximum occurs (0 width 1).
square (t, duty) Returns a vector the same length as t corresponding to a square wave
of period 2. The optional parameter duty generates a square wave with
a duty cycle specified by duty, which is the percentage of the period over
which the function is positive.
stepfun (t, t0) Returns a vector the same length as t with zeros where t < t0 and ones
where t t0.
MATLAB : Chapter 8. Numerical calculus and differential equations
ODE Solvers in the Control System Toolbox(7/7)
Example
0 1 2 3 4 5 6 7 8 9 10
0.5
0
0.5
1
1.5
Time
R
e
s
p
o
n
s
e
MATLAB : Chapter 8. Numerical calculus and differential equations
Advanced Solver Syntax(1/2)
The odeset Function
< Table 8.81 > Complete syntax of ODE solvers
Command Description
[t, y] = ode23 (ydot,
tspan, y0, options, p1,
p2, )
Solves the differential equation specified in the function the ydot,
whose inputs must be t and y and whose output must be a column vector
representing dy/dt; that is, f(t,y). The number of rows in this column vector must
equal the order of the equation. The vector tspan contains the starting and
ending values of the independent variable t, and optionally, any intermediate
values of t where the solution is desired. The vector y0 contains y(t
0
). The
function file must have two input arguments t and y even for equations where
f(t,y) is not a function of t.
The options argument is created with the odeset function, and p1, p2, are
optional parameters that can be passed to the function file ydot every time it is
called. If these optional parameters are used, but no options are set, use
options = [ ] as a placeholder.
The function file ydot can take additional input arguments. It has the form ydot (t,
y, flag, p1, p2, ), where flag is an argument that notifies the function ydot that
the solver is expecting a specific kind of information. The syntax for all the
solvers is identical to that of ode23.
Options = odeset
(name1, value1,
name2, value2, )
Creates an integrator options structure options to be used with the ODE solver,
in which the named properties have the specified values, where name is the
name of a property and value is the value to be assigned to the property. Any
unspecified properties have default values. odeset with no input arguments
displays all property names and their possible values.
) , (
.
y t f y =
MATLAB : Chapter 8. Numerical calculus and differential equations
Advanced Solver Syntax(2/2)
Stiff Differential Equations
A stiff differential equation is one whose response changes rapidly over a
time scale that is short compared to the time scale over which we are
interested in the solution.
A small step size is needed to solve for the rapid changes, but many steps
are needed to obtain the solution over the longer time interval, and thus a
large error might accumulate.
The four solvers specifically designed to handle stiff equations: ode15s (a
variableorder method), ode23s (a loworder method), ode23tb (another
loworder method), ode23t (a trapezoidal method).
SPaC, POSTECH 156
MATLAB
CHAPTER 7
Simulink
MATLAB : Chapter 9. Simulink
157
Simulation Diagram
Simulation diagram (block diagram)
Consider the equation
Simulation diagrams for
) ( 10
.
t f y =
}
= dt t f t y ) ( 10 ) (
) ( 10 ) ( t f t x =
}
= dt t x t y ) ( ) (
10
}
f(t) y(t) x(t) f y x
10
s
1
) ( 10
.
t f y =
MATLAB : Chapter 9. Simulink
158
Introduction to Simulink
Type Simulink
in the MATLAB
Command window
to start window.
The Simulink Library Browser
Type simulink
In the Command
Window
MATLAB : Chapter 9. Simulink
159
Introduction to Simulink
Create a new model
Click on the icon that resembles a
clean sheet of paper, or select New
from the File menu in the Browser.
Click
this icon
File New
Or
MATLAB : Chapter 9. Simulink
160
Introduction to Simulink
Doubleclick appropriate library.
See a list of blocks within that library.
Click on the block name or icon.
Hold the mouse button, and drag
it to the new model window.
release the button.
click, hold,
drag, and
release
MATLAB : Chapter 9. Simulink
161
Introduction to Simulink
Use the File menu in the model window to Open, Close, and Save model files.
To print, File print
Edit : to copy, cut and paste blocks.
you can also use mouse for these operations
MATLAB : Chapter 9. Simulink
162
Introduction to Simulink
Example
Simulink Solution of
Use Simulink to solve the following problem for 0 t 13.
The exact solution is
) sin( 10
.
t y =
) sin( 10 t
dt
dy
=
0 ) 0 ( = y
) cos 1 ( 10 ) ( t t y =
MATLAB : Chapter 9. Simulink
163
Introduction to Simulink
Start Simulink and open a new model window.
Select and place the Sine Wave block from the Source library.
MATLAB : Chapter 9. Simulink
164
Introduction to Simulink
Doubleclick to open the Block Parameters
window.
Make sure that Amplitude= 1, Frequency= 1,
Phase= 0, Sample time= 0
Then click OK.
MATLAB : Chapter 9. Simulink
165
Introduction to Simulink
Select and place the Gain block from the Math Operations library.
the Block Parameters window: the Gain value = 10.
Note that the value 10 then appears in the triangle.
Select and place the Integrator block from the Continuous library.
Initial condition=0 (because y(0)=0)
MATLAB : Chapter 9. Simulink
166
Introduction to Simulink
Select and place the Scope block from the Sinks library.
Connect each input and output port.
MATLAB : Chapter 9. Simulink
167
Introduction to Simulink
Click on the Simulation menu, and click the Configuration Parameters item.
(If you use MATLAB 6.5 or earlier, click Simulation parameters instead of
Configuration Parameters.)
Click on the solver tab, and enter 13 for the stop time.
Make sure the Start time is 0.
MATLAB : Chapter 9. Simulink
168
Introduction to Simulink
Run the simulation by clicking on the Simulation menu,
and clicking the Start item.
OR
MATLAB : Chapter 9. Simulink
169
Introduction to Simulink
After the simulation, doubleclick on the Scope block .
Doubleclick!
MATLAB : Chapter 9. Simulink
170
Linear StateVariable Models
Statevariable models can have
more than one input and more
than on output.
Simulink has the Statespace
block that represents the linear
statevariable model
Du Cx y Bu Ax x + = + = ,
.
MATLAB : Chapter 9. Simulink
171
Linear StateVariable Models
Example
Simulink Model of the TwoMass System
m1=5, m2=3, c1=4, c2=8, k1=1, and k2=4
The equations of motion are
These equations can be expressed in statevariable
form as
) ( 4 8 4 8 3
0 4 8 5 12 5
1 1 2 2 2
2 2 1 1 1
.
. ..
.
. ..
t f x x x x x
x x x x x
= + +
= + +
4 3
2 1
.
.
z z
z z
=
=
) 4 (
3
1
.
) 5 (
5
1
.
) ( 8 4 8
8 4 12
4 3 2 1 4
4 3 2 1 2
t f z z z z z
z z z z z
+ +
+ +
=
=
MATLAB : Chapter 9. Simulink
172
Linear StateVariable Models
Vector matrix form
) (
.
t Bf Az z + =
A =
0 1 0 0
1 12/5 4/5 8/5
0 0 0 1
4/3 8/3 4/3 8/3
0
0
0
1/3
B =
2
2
1
1
.
.
x
x
x
x
z1
z2
z3
z4
z = =
MATLAB : Chapter 9. Simulink
173
Linear StateVariable Models
Initinal conditions
Output equation
) ( : t Df Cz y output + =
1 0 0 0
0 0 1 0
C =
0
0
D =
0 ) 0 ( 2 , 5 . 0 ) 0 ( 2 , 0 ) 0 ( 1 , 2 . 0 ) 0 ( 1
. .
= = = = x x x x
MATLAB : Chapter 9. Simulink
174
Linear StateVariable Models
Create a new model window
Select and place the Step block from the Sources library.
Step time=0, Initial and Final values =0 and 1, Sample time=0
MATLAB : Chapter 9. Simulink
175
Linear StateVariable Models
Select and place the StateSpace
lock. Enter A,B,C,D. Then enter
initial condition.
0.2; 0; 0.5; 0
MATLAB : Chapter 9. Simulink
176
Linear StateVariable Models
Select and place the Scope block.
connect each port.
MATLAB : Chapter 9. Simulink
177
Linear StateVariable Models
experiment with different values of the Stop time until the Scope shows that
the steadystate response has been reached.
Ex) when stop time = 25
steadystate
MATLAB : Chapter 9. Simulink
178
PiecewiseLinear Models
Closedform solutions are not available for most nonlinear differential
equations, We must solve such equations numerically.
Ex)
Piecewiselinear models are actually nonlinear, although they may
appear to be linear.
Ex) a mass attached to a spring and sliding on a horizontal surface with
Coulomb friction.
0
.
5
..
= + + y y y y 0 ) sin(
.
= + y y 0
.
= + y y
0 ) (
0 ) (
. ..
. ..
s + +
> +
=
=
x x x
x x x
if mg t f k m
if mg t f k m
s
> +
= + =
0 1
0 1
) sing( ) sing( ) (
. . ..
.
.
x
x
x x x x
if
if
where mg t f k m
MATLAB : Chapter 9. Simulink
180
Simulink Model of a RocketPropelled
sled
A rocket propelled sled
Compute the sleds velocity v for 0t6 if v(0) = 0
The rocket thrust is 4000N and the sled mass is 450kg.
The sleds equation of motion is
.
450 4000cos( ) v u =
f
b
v
) / (
50
..
s rad
t
u =
MATLAB : Chapter 9. Simulink
181
Simulink Model of a RocketPropelled sled
To obtain (t)
Thus the equation of motion becomes
The solution is formally given by
2
0 0
0
100 50
50
.
..
.
t tdt dt
t dt
t t
t
t t
t
u u
u u
= =
=
} }
}
=
=
)
100
cos( 4000
.
450
2
t v
t
=
dt t t v
t
)
100
cos(
9
80
) (
0
2
}
=
t
MATLAB : Chapter 9. Simulink
182
Simulink Model of a RocketPropelled
sled
(a) Create a Simulink model to solve this problem for 0t10s.
(b) Now suppose that the engine angle is limited by a mechanical stop to
60 , which is 60/180 rad. Create a Simulink model to solve the problem.
Solution
(a)
create (t) by integrating the constant twice.
Constant block from the Sources library. Constant value=pi/50.
Trigonometric block from the Math Operations library. Function=cos.
) / (
50
..
s rad
t
u =
MATLAB : Chapter 9. Simulink
183
Simulink Model of a RocketPropelled
sled
Set the Stop time 10, run the
simulation, and examine the result
in Scope.
MATLAB : Chapter 9. Simulink
184
Simulink Model of a RocketPropelled
sled
(b)
modify the model as follows.
the Saturation block from the
Discontinuities library.
Upper limit= 60*pi/180,
Lower limit=0.
mux
Generate the
solution when the
engine angle =0.
mux
MATLAB : Chapter 9. Simulink
185
Simulink Model of a RocketPropelled
sled
Scope window
=0
0
MATLAB : Chapter 9. Simulink
186
The Relay Block
The Simulink Relay block is an example of something that is tedious to
program in MATLAB but is easy to implement in Simulink.
A graph of the logic of a relay.
The relay switches the output between two specified values, named On
and Off in the figure.
On
Off
SwOn SwOff
Off
On
SwOff
SwOn
The relay function. (a) The case where
On>Off. (b) The case where On<Off
(a)
(b)
MATLAB : Chapter 9. Simulink
187
Model of a RelayControlled Motor
The model of an armaturecontrolled dc motor
) (
) (
t T c i K
dt
d
I
t v K Ri
dt
di
L
d
e
T =
+ =
e
e
e
MATLAB : Chapter 9. Simulink
188
Model of a RelayControlled Motor
x1=i, x2=
R=0.6, L=0.002H, KT=0.04Nm/A, Ke=0.04Vs/rad, c=0.01Nms/rad, and
I=610^(5)kgm^2
Suppose we have a sensor that measure the motor speed, and we use the
sensors signal to activate a relay to switch the applied voltage v(t) between
0 and 100V to keep the speed between 250 and 350rad/s.
SwOff=250, SwOn=350, Off=100, On=0
2
1
.
.
x
x
=
2
1
x
x
R/L Ke/L
KT/I c/I
+
1/L 0
0 1/I
V(t)
Td(t)
On
Off
SwOn SwOff
MATLAB : Chapter 9. Simulink
189
Model of a RelayControlled Motor
Given parameter values
To examine the speed as output, we choose
300 20
666.7 166.7
A =
500 0
0 16667
B =
0 1
C =
0 0
D =
MATLAB : Chapter 9. Simulink
190
Model of a RelayControlled Motor
Create a new Simulink model.
Select and place a Step block
from the Sources library. Label it
Disturbance Step.
Step time=0.05, Initial and Final
time=0 and 3, Sample time=0
Select and place a Relay block
from the Discontinuities library.
Switchon and Switchoff
points=350 and 250,
Output when on and Output when
off=0 and 100.
MATLAB : Chapter 9. Simulink
191
Model of a RelayControlled Motor
Select and place the Mux block
from the signal Routing library.
Display option to Signals.
number of input=2.
Select and place the State
Space block from the
Continuous library.
enter the A,B,C,D.
enter [0;0] for the initial conditoin.
B tells 2 input, C and D tells 1
output.
MATLAB : Chapter 9. Simulink
192
Model of a RelayControlled Motor
Select and place the Scope
block from the Sinks library.
connect each port.
Stop time=0.1 and run the
simulation. (the plot of (t) in the
scope.)
Note:
Connect signal1(first input) to the output
of the Relay block
Connect signa2(second input) to the
output of the Disturbance Step
MATLAB : Chapter 9. Simulink
193
Model of a RelayControlled Motor
Relay logic scheme keeps the speed
within the desired limits of 250 and 350
before the disturbance torque starts to
act.
Speed oscillates.
When V=0, the speed decrease
because back emf, and viscous
damping.
The speed drops below 250 when the
disturbance torque starts to act,
because the V=0.
As soon as the speed drops for the
speed to increase because the motor
torque must now work against the
disturbance.
MATLAB : Chapter 9. Simulink
194
Model of a RelayControlled Motor
Speed becomes constant
V=100, the system achieves a steady
state condition in which the motor
torque equals the sum of the
disturbance torque and the viscous
damping torque. Thus the acceleration
is zero.
MATLAB : Chapter 9. Simulink
195
Model of a RelayControlled Motor
If you want examine the current i(t), change the
matrix C to [1,0], and run the simulation again.
SPaC, POSTECH 196
MATLAB
CHAPTER 92
Simulink
MATLAB : Chapter 9. Simulink
197
TransferFunction Models
massspringdamper system
As with the control System toolbox, Simulink can accepts a system description in transfer
function form and in statevariable form
if force f(t) is sinusoidal function, it is easy to use the MATLAB commands presented.
However, suppose that the force f(t) is created by applying a sinusoidal input voltage to a
hydraulic piston that has a deadzone nonlinearity. This means that the piston does not
generate a force until the input voltage exceeds a certain magnitude.
A graph of a particular deadzone nonlinearity is shown below.
) (t f y k y c y m = + +
  
1 0.8 0.6 0.4 0.2 0 0.2 0.4 0.6 0.8 1
0.5
0.4
0.3
0.2
0.1
0
0.1
0.2
0.3
0.4
0.5
Input
O
u
t
p
u
t
MATLAB : Chapter 9. Simulink
198
TransferFunction Models
[EXAMPLE 9.51] Response with a Dead Zone
Create and run a Simulink simulation of a massspringdamper model
m=1, c=2 and k=4
f(t) = sin(1.4t)
The system has the deadzone nonlinearity shown in Figure 9.51
Solution
Start Simulink and construct
fallowing Simulink model
) (t f y k y c y m = + +
  
MATLAB : Chapter 9. Simulink
199
TransferFunction Models
Solution (contd)
Details of Blocks
drag
doubleclick
& change
parameters
Simulink library
browser
MATLAB : Chapter 9. Simulink
200
TransferFunction Models
solution (contd)
Modification of the deadzone model to include a
Mux block
To plot both the input and the output of the
Transfer Fcn block versus time on the same graph.
(More informative)
drag
doubleclick
& change
parameters
MATLAB : Chapter 9. Simulink
201
Nonlinear StateVariable Models
Nonlinear models cannot be put into transferfunction form or the state
variable form.
However, they can be simulated in Simulink.
[EXAMPLE 9.61] Model of a Nonlinear Pendulum
I : the mass moment of inertia about the pivot.
I = 4, mgL = 10, c = 0.8
M(t) : a square wave with an amplitude of 3 and a frequency of 0.5Hz
initial conditions : = /4, = 0
Create a Simulink model for this system
g
m
L
Figure 9.61
A pendulum
) ( sin t M mgL c I = + +
  
u u u
) 0 (

u ) 0 ( u
MATLAB : Chapter 9. Simulink
202
Nonlinear StateVariable Models
Solution

=u e let
    ) ( sin 10 8 . 0 25 . 0 ) ( sin
1
t M t M mgL c
I
+ = + =
=

u e u e e
e u
Integrate both sides of each equation over time to obtain
 
}
}
+ =
=
dt t M
dt
) ( sin 10 8 . 0 25 . 0 u e e
e u
MATLAB : Chapter 9. Simulink
203
Nonlinear StateVariable Models
Solution (contd)
Construct following Simulink model
Select blocks and place them.
Doubleclick blocks and change parameters.
initial = 0
initial = pi/4
MATLAB : Chapter 9. Simulink
204
Nonlinear StateVariable Models
Solution (contd)
Details of new blocks
drag
doubleclick
& change
parameters
MATLAB : Chapter 9. Simulink
205
Nonlinear StateVariable Models
Solution (contd)
Simulation result
Note
To flip the box left to right, rightclick on it, select Filp
Fnc block : General expression block. Use u as input variable name.
MATLAB : Chapter 9. Simulink
206
Subsystems
To simulate a complex system, the diagram can become rather large
and therefore some what cumbersome.
Simulink, however, provides for the creation of subsystem blocks
Subsystem block
play a role analogous to that of subprograms in a programming language
a Simulink program represented by a single block.
can be used in other Simulink programs.
Example A Hydraulic System
MATLAB : Chapter 9. Simulink
207
Subsystems
Example A Hydraulic System
liquid mass density
cylindrical tank with a bottom area A
mass flow rate q
mi
(t)
total mass in the tank m = Ah
If the outlet is a pipe that discharges to atmospheric pressure p
a
and provides a resistance
to flow that is proportional to the pressure difference across its ends, then the outlet flow
rate is
where R is called the fluid resistance.
The transfer function is
mo mi
q q
dt
dh
A
dt
dm
= =
h
R
g
q
dt
dh
A
mo
=
R
gh
p p gh
R
q
a a mo
= + = ] ) [(
1
R g As s Q
s H
mi
/
1
) (
) (
+
=
MATLAB : Chapter 9. Simulink
208
Subsystems
Example A Hydraulic System (contd)
On the other hand, the outlet may be a valve or other restriction that provides nonlinear
resistance to the flow.In such cases, a common model is the signedsquareroot relation
where q
mo
is the outlet mass flow rate, R is the resistance, p is the pressure difference
across the resistance, and
in Simulink : sgn(u)*sqrt(abs(u)) (note: in Matlab~sign(u))
Consider the slightly different system
flow source q and two pumps that supply
liquid at the pressures p
l
and p
r
.
Suppose the resistances are nonlinear and
obey the signedsquareroot relation
then the model of the system is
) (
1
p SSR
R
q
mo
A =
< A A
> A A
= A
0
0
) (
p if p
p if p
p SSR
) (
1
) (
1
r
r
l
l
p p SSR
R
p p SSR
R
q
dt
dh
A + =
MATLAB : Chapter 9. Simulink
209
Subsystems
Create a subsystem block
drag the Subsystem block from the library
or first creation a Simulink model and then encapsulating
Create s subsystem block for the liquidlevel system shown in Figure 9.72.
First construct the Simulink model as fallow
input port
(Ports and
Subsystems
library)
output port
(Ports and
Subsystems
library)
MATLAB : Chapter 9. Simulink
210
Subsystems
Create s subsystem block (Contd)
create a bounding box surrounding the diagram. (holding the mouse button down, and
dragging)
choose Create Subsystem from the Edit menu. (or in the Rightclick menu)
The result
MATLAB : Chapter 9. Simulink
211
Subsystems
Connecting Subsystem Blocks
create a simulation of the system shown below
where the mass inflow rate q is a step function
Simulink model of the system
Doubleclick subsystem block Tank 1 and change
parameters.
1/R_l=0; 1/R_r=1/R_1; 1/rho*A=1/rho*A_1
initial condition of the integrator to h10
in Tank 2
1/R_l = 1/R_1; 1/R_r = 1/R_2; 1/rho*A=1/rho*A_2
initial condition of the integrator to h20
MATLAB : Chapter 9. Simulink
212
Subsystems
Running the model
in the Command window assign numerical values to the variables
>> A_1=2;A_2=5;rho=1.94;g=32.2;
>> R_1=20;R_2=50;q_1=0.3;h10=1;h20=10;
Simulation result
MATLAB : Chapter 9. Simulink
213
Dead Time in Models
Dead Time (transport delay)
a time delay between an action and its effect.
The transfer function for a deadtime process is
(from the shifting property of the Laplace transform)
Some systems have an unavoidable time delay in the interaction between components.
The delay often results from the physical separation of the components and typically
occurs as a delay between a change in the actuator signal and its effect on the
system being controlled, or as delay in the measurement of the output
Another, source of dead time is the computation time required for digital control computer
to calculate the control algorithm.
There are an infinite number of characteristic roots for a system with dean time.
The analysis of deadtime processes is difficult, and often simulation is the only practical
way to study such processes.
Easily simulated in Simulink. Using Transport Delay Block.
Ts
e
+ + +
= =
2 / 1
1 1
2 2
s T Ts e
e
Ts
Ts
MATLAB : Chapter 9. Simulink
214
Dead Time in Models
Consider the model of the height h of liquid in a tank.
input is a mass flow rate qi
it takes a time T for the change in input flow to reach the
tank following a change in the valve opening.
the transfer function
Simulink model for this system
1 5
2
) (
) (
+
=
s
e
s Q
s H
Ts
i
MATLAB : Chapter 9. Simulink
215
Dead Time in Models
Transport Delay block
in Continuous library
Doubleclick the block and set the delay to 1.25
Transfer Fcn (with initial outputs) block
Doubleclick the block and set the initial output to 0.2
The Saturation and Rate Limiter Blocks
suppose that the minimum and maximum flow rates available from the input flow valve are
0 and 2
In additional, some actuators have limits on how fast they can react. (to avoid damage to
the unit)
Saturation block
in Discontinuity library
Doubleclick the block and set the Upper limit to 2, the Lower limit to 0
Rate Limiter block
in Discontinuity library
Doubleclick the block and set the Rising slew rate to 2, the Falling slew rate to 0
MATLAB : Chapter 9. Simulink
216
Dead Time in Models
A Control System
The Simulink model shown in Figure 9.81 is for a specific type of control system called a PI
controller.
whose response f(t) to the error signal e(t) is the sum of a term proportional to the error signal
and a term proportional to the integral of the error signal.
where K
P
and K
I
are called the proportional and integral gains.
The error signal e(t) is the difference between the unitstep command representing the desired
height and the actual height.
In transform notation
In Figure 9.81, we used the values K
P
=4 and K
I
=5/4.
Simulation Result
Stop time to 30
}
+ =
t
I P
dt t e K t e K t f
0
) ( ) ( ) (
) ( ) ( ) ( ) ( s E
s
K
K s E
s
K
s E K s F
I
p
I
P

.

\

+ = + =
MATLAB : Chapter 9. Simulink
217
Simulation of a Vehicle Suspension
Often in the design of an engineering system, we must eventually deal
with nonlinearities in the system and with more complicated inputs such
as trapezoidal functions, and this must often be dome with simulation.
In this section we introduce four additional Simulink elements that enable
us to model a wide range of nonlinearities and input functions,
the Derivative block,
the Signal Builder block,
the LookUp Table block, and
the MATLAB Fcn block
As our example, we will use the
singlemass suspension model
shown in Figure 9.91
MATLAB : Chapter 9. Simulink
218
Simulation of a Vehicle Suspension
Singlemass model of a vehicle suspension
the spring and damper forces fs and fd have the nonlinear models shown in
Figures 9.91 and 9.93
The bump is represented by the trapezoidal function y(t) shown in Figure 9.94
MATLAB : Chapter 9. Simulink
219
Simulation of a Vehicle Suspension
The system model from Newtons law is
where m = 400 kg, is the nonlinear spring fuction shown in Figure 9.92
and is the nonlinear damper function shown n Figure 9.93
The corresponding simulation diagram
)
. .
( ) (
..
x y f x y f x m
d s
+ =
) ( x y f
s
)
. .
( x y f
d
MATLAB : Chapter 9. Simulink
220
Simulation of a Vehicle Suspension
Simulink model of a vehicle suspension system.
The Derivative Block
Simulink uses numerical methods,
it computes derivatives only approximately
in Continuous library
The Signal Builder Blocks
in Source library
doubleclick and create the function
shown in Figure 9.94
MATLAB : Chapter 9. Simulink
221
Simulation of a Vehicle Suspension
The lookUp Table Block
The spring function fs is created with the LookUp Table block.
In Lookup Tables library
doubleclick on it and enter [0.5, 0.1, 0, 0.1, 0.5] for the Vector of input values
and [4500, 500, 0, 500, 4500] for the Vector of output values.
To Workspace block and the Clock
enable us to plot x(t) and y(t)x(t) versus t in the MATLAB Command window.
The MATLAB Fcn Block
we must write a userdefined
function to describe the damper function.
doubleclick on the block and
change function name.
MATLAB : Chapter 9. Simulink
222
Simulation of a Vehicle Suspension
Simulation Result
You can plot the response x(t) in the Command window as follows
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
0.2
0.15
0.1
0.05
0
0.05
0.1
0.15
0.2
0.25
0.3
t (s)
x
(
m
)
MATLAB
CHAPTER 10
Symbolic processing with MATLAB
MATLAB : Chapter 10. Symbolic processing with MATLAB
OUTLINE
Symbolic expressions and algebra(10)
Algebraic and transcendental equations(3)
Calculus (9)
Differential Equations (6)
MATLAB : Chapter 10. Symbolic processing with MATLAB
Symbolic expressions and algebra(1/10)
The sym function
Ex >>x = sym ('x')
>>x = sym ('x', 'real')
>>syms x y u v
>>pi=sym('pi')
>>fraction=sym('1/3')
>>sqroot2=sym('sqrt(2)')
Symbolic expressions
ex >>syms x y
>>s = x + y
>>r = sqrt(x^2+y^2)
ex >>symbolic matrix A
>>n=3
>>syms x;
>>A=x.^((0:n)'*(0:n))
A=
[1,1,1,1]
[1,x,x^2,x^3]
[1,x^2,x^4,x^6]
[1,x^3,x^6,x^9]
MATLAB : Chapter 10. Symbolic processing with MATLAB
Symbolic expressions and algebra(2/10)
expand (E)
ex >>syms x y
>>expand((x+y)^2)
% applies algebra rules
ans =
x^2+2*x*y+y^2
>>expand(sin(x+y))
% applies trig identities
ans =
>>sin(x)*cos(y)+cos(x)*sin(y)
>>simplify(6*((sin(x))^2+(cos(x))^2))
% applies another trig identity
ans =
6
Manipulating expressions
collect (E)
ex >>syms x y
>>E=(x5)^2+(y3)^2;
>>collect (E)
ans =
x^210*x+25+(y3)^2
>>collect(E,y)
ans =
y^26*y+(x5)^2+9
MATLAB : Chapter 10. Symbolic processing with MATLAB
Symbolic expressions and algebra(3/10)
factor (E)
ex >>syms x y
>>factor(x^21)
ans =
(x1)*(x+1)
simplify (E)
ex >>syms x y
>>simplify(x*sqrt(x^8*y^2))
ans =
x*(x^8*y^2)^(1/2)
simple (E)
[r, how] = simple (E)
Ex> >>syms x y
>>E1=x^2+5; % define two expressions
>>E2=y^32;
>>E3=x^3+2*x^2+5*x+10; % define a third
expressions
>>S1=E1+E2 % add the expressions
S1 =
x^2+3+y^3
>>S2=E1*E2 % multiply the expressions
S2 =
(x^2+5)*(y^32)
>>expand(S2) % expand the product
ans =
x^2*y^32*x^2+5*y^310
>>S3=E3/E1 % divide two expressions
S3 =
(x^3+2*x^2+5*x+10)/(x^2+5)
>>simplify(S3) % see if some terms cancel
ans =
x+2
MATLAB : Chapter 10. Symbolic processing with MATLAB
Symbolic expressions and algebra(4/10)
[num den] = numden (E)
ex >> syms x
>> E1=x^2+5;
>> E4=1/(x+6);
>> [num, den]=numden(E1+E4)
num =
x^3+6*x^2+5*x+31
den =
x+6
double (E)
ex >> sqroot2=sym('sqrt(2)');
>> y=6*sqroot2
y =
6*2^(1/2)
>> z=double(y)
z =
8.4853
MATLAB : Chapter 10. Symbolic processing with MATLAB
Symbolic expressions and algebra(5/10)
poly2sym (p)
poly2sym (p, 'v')
ex >> poly2sym([2,6,4])
ans =
2*x^2+6*x+4
>> poly2sym([5,3,7],'y')
ans =
5*y^23*y+7
sym2poly (E)
ex >> syms x
>> sym2poly (9*x^2+4*x+6)
ans =
9 4 6
pretty (E)
ex >> E5=1/(x+6);
>> pretty(E5)
1

x + 6
subs (E,old,new)
ex >> syms x y
>> E=x^2+6*x+7;
>> F=subs(E,x,y)
F =
y^2+6*y+7
ex >> syms t
>> f=sym('f(t)');
>> g=subs(f,t,t+2)f
g =
f(t+2)f(t)
MATLAB : Chapter 10. Symbolic processing with MATLAB
Symbolic expressions and algebra(6/10)
ex (n1)!
>> kfac=sym('k!');
>> syms k n
>> E=subs(kfac,k,n1)
E =
(n1)!
>> expand(E)
ans =
n!/n
To compute a numeric factorial
ex >> 5!
>> factorial(5)
>> prod(1:5)
ex >> syms a b x
>> E=a*sin(b);
>> F=subs(E,{a,b},{x,2})
F =
x*sin(2)
MATLAB : Chapter 10. Symbolic processing with MATLAB
Symbolic expressions and algebra(7/10)
Evaluating expressions
ex >> syms x
>> E=x^2+6*x+7;
>> G=subs(E,x,2)
G =
23
>> class(G)
ans =
double
digit (d) to change the number of digits MATLAB uses for calculating and evaluating expressions
vpa (E) to compute the expression E to the number of digits specified by the default value of 32 or the
current setting of digits
vpa (E,d) to compute the expression E using d digits
MATLAB : Chapter 10. Symbolic processing with MATLAB
Symbolic expressions and algebra(8/10)
Plotting expressions
ezplot (E)
explot ( E, [xmin xmax] )
ex >> syms x
>> E=x^26*x+7;
>> ezplot(E,[2 6])
MATLAB : Chapter 10. Symbolic processing with MATLAB
Symbolic expressions and algebra(9/10)
Order of precedence
ex syms x
E=x^26*x+7;
F=E/3
Functions for creating and evaluating symbolic expressions
Command Description
class (E) Returns the class of the expression E.
digits (d) Sets the number of decimal digits used to do variable precision arithmetic. The default is 32 digits.
double (E) Converts the expression E to numeric form.
ezplot (E) Generates a plot of a symbolic expression E, which is a function of one variable. The default range of the
independent variable is the interval [2, 2] unless this interval contains a singularity. The optional form
ezplot (E,[xmin xmax]) generates a plot over the range from xmin to xmax.
findsym(E) Finds the symbolic variables in a symbolic expression or matrix, where E is a scalar or matrix symbolic
expression, and returns a string containing all the symbolic variables appearing in E. the variables are
returned in alphabetical order and are separated by commas. If no symbolic variables are found, findsym
returns the empty string.
findsym(E,n) Returns the n symbolic variables in E closest to x, with the tie breaker going to the variable closer to z.
[num den]=numden(E) Returns two symbolic expressions that represent the numerator expression num and denominator
expression den for the rational representation of the expression E.
x=sym (x) Creates the symbolic variable with name x. typing x=sym (x,real) tells MATLAB to assume that x is real.
Typing x=sym (x,unreal) tells MATLAB to assume that x is not real.
syms x y u v Creates the symbolic variables x,y,u,and v. when used without arguments, syms lists the symbolic objects
in the workspace.
vpa (E,d) Sets the number of digits used to evaluate the expression E to d. typing vpa(E) causes E to be evaluated
to the number of digits specified by the default value of 32 or by the current setting of digits.
F = 1/3*x^2+2*x7/3
normally F=  (x26x+7)/3
MATLAB : Chapter 10. Symbolic processing with MATLAB
Symbolic expressions and algebra(10/10)
Functions for creating and evaluating symbolic expressions
Command Description
collect (E) Collects coefficients of like powers in the expression E.
expand (E) Expands the expression E by carrying out powers.
factor (E) Factors the expression E.
poly2sym (p) Converts a polynomial coefficient vector p to a symbolic polynomial. The form
poly2sym(p,v) generates the poly
pretty (E) Displays the expression E on the screen in a form that resembles typeset mathematics.
simple (E) Searches for the shortest form of the expression E in terms of number of characters. When
called, the function displays the results of each step of its search. When called without the
argument, simple acts on the previous expression. The form [ r, how] = simple (E) does not
display intermediate steps, but saves those steps in the string how. The shortest form found
is stored in r.
simplify (E) Simplify the expression E using Maples simplification rules.
subs (E,old,new) Substitutes new for old in the expression E, where old can be a symbolic variable or
expression, new can be a symbolic variable ,expression ,or matrix, or a numeric value or
matrix.
sym2poly (E) Converts the expression E to a polynomial coefficient vector.
MATLAB : Chapter 10. Symbolic processing with MATLAB
Algebraic and transcendental equations(1/3)
The solve Function
(equation x+5=0)
ex >> eq1='x+5=0';
>> solve(eq1)
ans =
5
ex >> solve('x+5=0')
>> syms x
ans =
5
ex >> solve(x+5)
ans =
5
ex >> syms x
>> x=solve(x+5)
x =
5
(equation )
ex >> solve('exp(2*x)+3*exp(x)=54')
ans =
log(9)
log(6)
ex >> eq2='y^2+3*y+2=0';
>> solve(eq2)
ans =
[2]
[1]
ex >> eq3='x^2+9*y^4=0;
>> solve(eq3) % Note that x is presumed to ve the unknown
variable
ans =
[3*i*y^2]
[3*i*y^2]
54 3
2
= +
x x
e e
MATLAB : Chapter 10. Symbolic processing with MATLAB
Algebraic and transcendental equations(2/3)
solve ( E, 'v')
ex >> solve('b^2+8*c+2*b=0') % solves for c because
it is closer to x
ans =
1/8*b^21/4*b
ex >> solve('b^2+8*c+2*b=0','b') % solves for b
ans =
[ 1+(18*c)^(1/2)]
[ 1(18*c)^(1/2)]
[x ,y] = solve (eq1,eq2)
ex >> eq4='6*x+2*y=14';
>> eq5='3*x+7*y=31';
>> solve(eq4,eq5)
ans =
x : [1x1 sym]
y : [1x1 sym]
>> x=ans.x
x =
1
>> y=ans.y
y =
4
ex >> [x ,y] = solve(eq4,eq5)
>> S=solve(eq4,eq5)
S=
x : [1x1 sym]
y : [1x1 sym]
>> S.x
ans=
1
>> S.y
ans =
4
MATLAB : Chapter 10. Symbolic processing with MATLAB
Algebraic and transcendental equations(3/3)
Command Description
solve (E)
Solves a symbolic expression or equation represented by the
expression E. if E represents an equation, the equations expression
must be enclosed in single quotes. If E represents an expression,
then the solution obtained will be the roots of the expression E; that is,
the solution of the equation E=0. You need not declare the symbolic
variable with the sym or syms function before using solve.
solve (E1,,En) Solves multiple expressions or equations
S= solve (E) Saves the solution in the structure S.
Functions for solving algebraic and transcendental equations
MATLAB : Chapter 10. Symbolic processing with MATLAB
Calculus (differentiation) (1/9)
diff (E)
1
=
n
n
nx
dx
dx
ex
>> syms n x y
>> diff(x^n)
ans =
x^n*n/x
>> simplify(ans)
ans =
x^(n1)*n
x dx
x d 1 ln
=
ex
>> diff(log(x))
ans =
1/x
x x
dx
x d
cos sin 2
sin
2
=
ex
>> diff((sin(x)^2)
ans =
2*sin(x)*cos(x)
y
dy
y d
cos
sin
=
ex
>> diff((sin(y))
ans =
cos(y)
MATLAB : Chapter 10. Symbolic processing with MATLAB
Calculus (differentiation) (2/9)
) sin( ) , ( xy y x f =
) cos(xy y
dx
df
=
2
x
ex
>> diff(sin(x*y))
ans =
cos(x*y)*y
ex
1) >> diff(sin(x*y))
ans =
cos(x*y)*y
2) >> E=x^2;
>> diff(E)
ans=
2*x
3) >> syms x
>> diff(x^2)
ans =
2*x
) cos(
)] sin( [
2
xy x
y
xy x
=
c
c
ex
>> syms x y
>> diff(x*sin(x*y),y)
ans =
x^2*cos(x*y)
diff (E, v)
diff (E, n)
diff (E, v, n)
x
dx
x d
6
) (
2
3 2
= ex
>> syms x
>> diff(x^3,2)
ans =
6*x
) sin(
)] sin( [
3
2
2
xy x
y
xy x
=
c
c
ex
>> syms x y
>> diff(x*sin(x*y),y,2)
ans =
x^3*sin(x*y)
MATLAB : Chapter 10. Symbolic processing with MATLAB
Calculus (integration) (3/9)
int (E)
ex >> syms x
>> int(2*x)
ans =
x^2
ex
>> syms n x y
>> int(x^n)
ans =
x^(n+1)/(n+1)
>> int(1/x)
ans =
log(x)
>> int(cos(x))
ans=
sin(x)
>> int(sin(y))
ans=
cos(y)
1
1
+
=
+
}
n
x
dx x
n
n
x dx
x
ln
1
=
}
}
= x xdx sin cos
}
= y ydy cos sin
MATLAB : Chapter 10. Symbolic processing with MATLAB
Calculus (integration) (4/9)
x
x
dn x
n
n
ln
=
}
ex
>> syms n x
>> int(x^n,n)
ans =
1/log(x)*x^n
int (E, v)
int (E, a, b) 39
3
5
2
5
2
3
2
= =
}
x
dx x ex
>> syms x
>> int(x^2,2,5)
ans =
39
MATLAB : Chapter 10. Symbolic processing with MATLAB
Calculus (integration) (5/9)
3 3
3 3
2
a b
dx x
b
a
=
}
int (E, v, a, b)
x
y
x dy xy
3
125
3
5
0
3
5
0
2
= =
}
ex
>> syms x y
>> int(x*y^2,y,0,5)
ans =
125/3*x
int (E, m, n)
ex
>> syms a b x
>> int(x^2,a,b)
ans =
1/3*b^31/3*a^3
t e x xdx
t
x
dx x
t
e
t
e
t
t
t
t
t
cos ) cos( cos sin
2
1
2
1
2
2
1
2
1
+ = =
= =
}
}
ex
>> syms t x
>> int(x,1, t)
ans =
1/2*t^21/2
>> int(sin(x),t,exp(t))
ans =
cos(exp(t))+cos(t)
1 ln
1
1
=
}
x dx
x
ex
>> syms x
>> int(1/(x1))
ans =
log(x1)
>> int(1/(x1),0,2)
ans =
NaN
:singularity at x=1
MATLAB : Chapter 10. Symbolic processing with MATLAB
Calculus (Taylor series) (6/9)
Taylors theorem
taylor (f, n, a)
ex < < + + = x
x x x
x x ,
! 7 ! 5 ! 3
sin
7 5 3
< < + + = x
x x x
x ,
! 6 ! 4 ! 2
1 cos
6 4 2
< < + + + + + = x
x x x
x e
x
,
! 4 ! 3 ! 2
1
4 3 2
n
b x n
n
n
a x
dx
f d
n
R ) (
!
1


.

\

=
= n
k
a x k
k
a x a x
R a x
dx
f d
k
a x
dx
f d
a x
dx
df
a f x f + +


.

\

+ +


.

\

+ 
.

\

+ =
= = =
) (
!
1
) (
2
1
) ( ) ( ) (
2
2
2
,
>> syms x
>> f=exp(x);
>> taylor(f,4)
ans =
1+x+1/2*x^2+1/6*x^3
>> taylor(f,3,2)
ans =
exp(2)+exp(2)*(x2)+1/2*exp(2)*(x2)^2
ex
] ) 2 (
2
1
) 2 ( 1 [
2 2
+ + x x e =( )
MATLAB : Chapter 10. Symbolic processing with MATLAB
Calculus (sums) (7/9)
symsum (E)
S = symsum (E, a, b)
>> syms k n
>> symsum(k,0,10)
ans =
55
>> symsum(k,0,n1)
ans =
1/2*n^21/2*n
>> factor(ans)
ans =
1/2*n*(n1)
>> symsum(k^2,1,4)
ans =
30
) ( ) 2 ( ) 1 ( ) ( ) ( b E a E a E a E x E
b
a x
+ + + + + + =
=
) 1 ( ) 2 ( ) 1 ( ) 0 ( ) (
1
0
+ + + + =
=
x E E E E x E
x
x
ex 55 10 9 3 2 1 0
10
0
= + + + + + + =
=
k
k
n n n k
n
k
2
1
2
1
1 3 2 1 0
2
1
0
= + + + + + =
=
30 16 9 4 1
4
1
2
= + + + =
= k
k
ex
MATLAB : Chapter 10. Symbolic processing with MATLAB
Calculus (limits) (8/9)
limit (E, a) ( )
limit (E) : limit as
limit (E, v, a) : limit as
>> syms h x
>> limit((x3)/(x^29),3)
ans =
1/6
>> limit((sin(x+h)sin(x))/h,h,0)
ans =
cos(x)
limit (E, v, a, 'right')
limit (E, v, a, left')
0 x
) ( lim x E
a x
ex
>> syms x
>> limit(1/x,x,0,'left')
ans =
Inf
>> limit(1/x,x,0,'right')
ans =
Inf
=
x
1
lim
=
x
1
lim
0 x
+ 0 x
ex
>> syms a x
>> limit(sin(a*x)/x)
ans =
a
a
x
ax
=
) sin(
lim
0 x
a v
ex
6
1
9
3
lim
2
=
x
x
h
x h x ) sin( ) sin(
lim
+
3 x
0 h
MATLAB : Chapter 10. Symbolic processing with MATLAB
Calculus (9/9)
Command Description
diff (E) Returns the derivative of the expression E with respect to the default independent variable.
diff (E,v) Returns the derivative of the expression E with respect to the variable v.
diff (E,n) Returns the nth derivative of the expression E with respect to the default independent variable.
diff (E,v,n) Returns the nth derivative of the expression E with respect to the variable v.
int (E) Returns the integral of the expression E with respect to the default independent variable.
int (E,v) Returns the integral of the expression E with respect to the variable v.
int (E,a,b) Returns the integral of the expression E with respect to the default independent variable over the interval [a,b],
where a and b are numeric quantities.
int (E,v,a,b) Returns the integral of the expression E with respect to the variable v over the interval [a,b], where a and b are
numeric quantities.
int (E,m,n) Returns the integral of the expression E with respect to the default independent variable over the interval [m,n],
where m and n are symbolic expressions.
limit (E) Returns the limit of the expression E as the default independent variable goes to 0.
limit (E,a) Returns the limit of the expression E as the default independent variable goes to a.
limit (E,v,a) Returns the limit of the expression E as the variable v goes to a.
limit (E,v,a,d) Returns the limit of the expression E as the variable v goes to a from the direction specified by d, which may be
right or left.
symsum (E) Returns the symbolic summation of the expression E.
taylor (f,n,a) Gives the first n1 terms in the Taylor series for the function defined in the expression f, evaluated at the point
x=a. If the parameter a is omitted, the function returns the series evaluated at x=0.
Symbolic calculus functions
MATLAB : Chapter 10. Symbolic processing with MATLAB
Differential Equations (1/6)
Solving a Single Differential Equation
The dsolve functions syntax: dsolve (eqn) returns a symbolic solution of the
ODE specified by the symbolic expression eqn.
The uppercase letter D the first derivative, D2 the second derivative.
(ex) Dw dw/dt.
Cannot use uppercase D as symbolic variable when using the dsolve function.
(example)
12 2 = + y
dt
dy
t
e C t y
2
1
6 ) (
+ = Analytic solution:
A symbolic solution using the dsolve function.
MATLAB : Chapter 10. Symbolic processing with MATLAB
Differential Equations (2/6)
Solving Sets of Equations
The appropriate syntax: dsolve (eqn1, eqn2,) returns a symbolic solution
of the set of equations specified by the symbolic expressions eqn1 and eqn2.
(example)
y x
dt
dy
y x
dt
dx
3 4
4 3
+ =
+ =
Analytic solution:
t e C t e C t y
t e C t e C t x
t t
t t
4 cos 4 sin ) (
4 sin 4 cos ) (
3
2
3
1
3
2
3
1
+ =
+ =
MATLAB : Chapter 10. Symbolic processing with MATLAB
Differential Equations (3/6)
Specifying Initial and Boundary Conditions
The appropriate syntax: dsolve(eqn,cond1,cond2) returns a symbolic
solution of the ODE specified by the symbolic expression eqn, subject to the
conditions specified in the expressions cond1, cond2, and so on.
(example)
2
2
2
, (0) 1, (0) 0
d y
c y y y
dt
= = = 2 / ) ( ) (
ct ct
e e t y
+ = Analytic solution:
MATLAB : Chapter 10. Symbolic processing with MATLAB
Differential Equations (4/6)
Plotting the Solution (1)
The ezplot function can be used to plot the solution
(example)
0 ) 0 ( ), 4 sin( 4 10 10 = + = + y t y
dt
dy
Analytic solution:
t
e t t t y
10
29
25
) 4 sin(
29
10
) 4 cos(
29
4
1 ) (
+ =
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2
t
14/29 cos(4 t)+10/29 sin(4 t)25/29 exp(10 t)
MATLAB : Chapter 10. Symbolic processing with MATLAB
Differential Equations (5/6)
Plotting the Solution (2)
Sometimes the ezplot function uses too few values of the independent variable
and thus does not produce a smooth plot.
To override the spacing chosen by the ezplot function, you can use the subs
function to substitute an array of values for the independent variable.
Define t to be a symbolic variable.
MATLAB : Chapter 10. Symbolic processing with MATLAB
Differential Equations (6/6)
(Table 10.41) The dsolve function
Command Description
dsolve(eqn) Returns a symbolic solution of the ODE specified by the symbolic
expression eqn. Use the uppercase letter D to represent the first
derivative; use D2 to represent the second derivative, and so on.
Any character immediately following the differentiation operator is
taken to be the dependent variable.
dsolve(eqn1,eqn2,) Returns a symbolic solution of the set of equations specified by
the symbolic expressions eqn1, eqn2, and so on.
dsolve(eqn,cond1,cond2,) Returns a symbolic solution of the ODE specified by the symbolic
expression eqn, subject to the conditions specified in the
expressions cond1, cond2, and so on. If y is the dependent
variable, these conditions are specified as follows: y(a) = b, Dy(a)
= c, D2(a) = d, and so on.
dsolve(eqn1,eqn2,,cond1,cond2,) Returns a symbolic solution of a set of equations specified by the
symbolic expressions eqn1, eqn2, and so on, subject to the initial
conditions specified in the expressions cond1, cond2, and so on.