bai giang matlab_55m

252
MATLAB BEGINNING

Upload: phan-minh-tan

Post on 14-Apr-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 1/252

MATLAB

BEGINNING

Page 2: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 2/252

MATLAB

Machine Code

MATLAB – High Level Programming Language

Assembly

Fortran C C++

BASIC JAVA

MATLAB

Easy Development

EfficientOperation

Page 3: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 3/252

MATLAB

CHAPTER 1An Overview of MATLAB

Page 4: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 4/252

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. ValentinePublisher : Elsivier Year : 2007

Page 5: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 5/252

MATLAB : Chapter 1. An Overview of MATLAB

Starting MatlabThe default MATLAB Desktop.

Page 6: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 6/252

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: a-b

ba

ab

a/ b

b

b

b

a

b \aa

b

Scalar arithmetic operations

Page 7: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 7/252

MATLAB : Chapter 1. An Overview of MATLAB

Operations (2/2)

Calculation result is savedto „ans ‟by default : ans = 9

6 is saved to ans by using ans one

more time

1.5 is saved to the variable „a‟byassign „a‟as the storing place

In the Matlab, „\ ‟= „ \‟

Page 8: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 8/252

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 xx = x + 2 : add 2 to the current value of xWorkspace : the names and values of any variables in use in thecurrent work session

Commands for managing the worksession

clc clears the Command window

clear Removes all variables frommemory

exist(„name‟) Determines if a file or variableexists having the name ‟name‟

quit Stops MATLAB

who Lists the variable currently inmemory

whos Lists the current variables andsizes, and indicates if they haveimaginary parts

: Colon; generates and arrayhaving regularly spacedelements

, Comma; separates elements of an array

; Semicolon; suppresses screenprinting; also denotes a new rowin an array

… Ellipsis; continues a line

Page 9: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 9/252

MATLAB : Chapter 1. An Overview of MATLAB

recall feature, and special variable

recall featurerecall a previously typed function or variablee.g.

up-arrow key( ↑) & down -arrow key(↓): move up and down through thepreviously typed lines one line at a time.Tab key: automatically completes the name of a function, variable, or file if youtype 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

Page 10: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 10/252

MATLAB : Chapter 1. An Overview of MATLAB

Complex Number Operations

„;‟ is a command whichleads to a new line, alsoomits calculation results.

Page 11: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 11/252

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.379243784781294e-04

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

Page 12: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 12/252

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 bracketse.g .

>> x = [0, 1, 3, 6]

You need not type all the numbers in the array if they are regularlyspaced

e.g.

>> u = [0: 0.1: 10] u = [0, 0.1, 0.2, 0.3, … , 9.8, 9.9, 10]

Page 13: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 13/252

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

Page 14: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 14/252

MATLAB : Chapter 1. An Overview of MATLAB

Mathematical functions

Some commonly usedmathematical 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 functionsuse radian measure

xe

x

xn xog 10

xosxinxan

xos - 1

xin- 1

xan - 1

Page 15: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 15/252

MATLAB : Chapter 1. An Overview of MATLAB

Working with Files

M-file : MATLAB function files and program files are saved with theextension .m , and called M-files .

MAT-fi le : save the names and values of variables .

ASCII-file : files written in a specific format designed to make themusable to a wide variety of software.

Page 16: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 16/252

MATLAB : Chapter 1. An Overview of MATLAB

System, directory, and file commands

system, directory, and file commands

addpath d i rname Adds the directory dirname to the search path.

cd d i rname Changes the current directory to dirname .

dir Lists all files in the current directory.

dir d i rname 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 d i rname Removes the directory dirname from the search path.

what Lists the MATLAB-specific files found in the current working directory. Most datafiles and other non-MATLAB files are not listed. Use di r to get a list of all files.

what d i rname Lists the MATLAB-specific files in directory dirname .

Page 17: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 17/252

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 andy 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).

Page 18: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 18/252

MATLAB : Chapter 1. An Overview of MATLAB

Plotting with MATLABVariable pairs must be written.(x,y) and (x,z) are pairs,so express „plot(x,y,x,z) ‟

Page 19: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 19/252

MATLAB : Chapter 1. An Overview of MATLAB

Linear Algebra Equations

the left division operator(\)e.g.

64 zyx

5 zyx

7 0z2yx

Matlab ‟s basic unit is „matrix ‟

Page 20: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 20/252

MATLAB : Chapter 1. An Overview of MATLAB

Statistics, Calculus, and Processing

Statisticsperform statistical calculations and other types of datamanipulation.

Numerical Calculus, Differential Equations, and SimulinkMATLAB can numerically compute the derivative andthe integral

Symbolic Processingobtain the derivative and the integral insymbolic form (a formula instead of as a set of numericalvalues)

dy/dx d x

dy/dx d x

Page 21: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 21/252

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 sc r ip t files ( c o m m a n d s files): store the commands in script files M-files

sc r ip t files:when need to use many commands or arrays withmany elements

func t ion files:when need to repeat the operation of a set of commands

Page 22: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 22/252

MATLAB : Chapter 1. An Overview of MATLAB

Script Files and the Editor/Debugger(2/2)

M-file make and save

Page 23: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 23/252

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 screen‟s 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 thekeyboard, and stores the value in x.

x = input („text‟ , ‟s‟) Displays the text in quotes, waits for user input from thekeyboard, 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.

Page 24: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 24/252

MATLAB : Chapter 1. An Overview of MATLAB

The MATLAB Help System(1/4)

Help Browser Graphical user interfacefind information, view online documentation

Help Functionshelp, lookfor, docdisplay syntax information for specified function

Other Resourcesrun demos, contact technical support, participate in a newsgroup.The MathWorks Website

the home of MATLAB.http://www.mathworks.com

Page 25: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 25/252

MATLAB : Chapter 1. An Overview of MATLAB

The MATLAB Help System(2/4)- Help Browser

The MATLAB Help Browser Contents: acontents listing tab

Index: a globalindex tab

Search: a searchtab having a findfunction and fulltext search features

Demos: abookmaking tab tostart built-indemonstrations

Page 26: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 26/252

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 func t ion Displays the documentation for the MATLAB function func t ion

doc t o o l b o x /func t ion Displays the documentation for the specified toolbox function

doc t o o l b o x Displays the documentation road map page for the specified toolbox

help Displays a list all the function directories, with a description of thefunction category each represents.

help func t ion Displays in the Command window a description of the specified

function func t ion

helpwin top ic Displays the help text for the specified top ic inside the desktop HelpBrowser window

lookfor top ic Displays in the Command window a brief description for all functionswhose description includes the specified keyword top ic

type f i lename Displays the M-file f i lename without opening it with a text editor.

Page 27: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 27/252

MATLAB : Chapter 1. An Overview of MATLAB

The MATLAB Help System(4/4)- Help Functions

Examples

Page 28: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 28/252

28

MATLAB

CHAPTER 2Numeric, Cell, and Structure Arrays

Page 29: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 29/252

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

29

Arrays

Arrays : Collection of numbersthe basic building block in MATLABaddition, subtraction, multiplication, division, and exponentiationpolynomial algebra and root

Available classes of arrays in MATLAB 7

numeric arrays : contains only numeric values cell arrays : access data by its locationstructure arrays : access data by name

Array

numeric character logical cell structure functionhandle

Java

Page 30: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 30/252

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

30

Arrays

Cartesian coordinates x, y, and zunit vector i, j, kexpress the vector p = x i + y j + z ke.g.

p = 5 i + 7 j + 2 kin 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

Page 31: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 31/252

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

31

Arrays

Creating Vectors in MATLABMATLAB 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 usetranspose

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 Ch 2 N i C ll d S A

Page 32: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 32/252

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

32

Arrays

Creating Vectors in MATLABGenerate 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 <= nx = [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 commandlinspace(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 Ch 2 N i C ll d S A

Page 33: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 33/252

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

33

ArraysTwo-Dimensional Arrays

An array can have multiple rows, multiple columns, or bothcalled a matrix

.

Creating MatricesSpace or commas separate elements in different columnsSemicolons 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]) >

7316

1042M

[1, 3, 5; 7, 9, 11]

[a; b]

[a b]

1197

531

1197531

MATLAB Ch t 2 N i C ll d St t A

Page 34: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 34/252

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

34

ArraysArray Addressing

The row number is always listed firstThe 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 elementsA( : , 3) denotes all the elements in the third column of the matrix A

C = B(2:3, 1:3)

948

7316C

1715123

25948

187316

131042

B

The general indexes of two dimensional array

MATLAB : Chapter 2 Numeric Cell and Structure Arrays

Page 35: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 35/252

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

35

ArraysThe 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 >

751

496A

A(1,5) = 300751

30496A

B = A(:,5:-1:1)

15700

69403B

MATLAB : Chapter 2 Numeric Cell and Structure Arrays

Page 36: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 36/252

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

36

ArraysSome 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 thematrix 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 thelargest elements in each column if A is a matrix. If any of the elements are complex, max(A) returns theelements 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

Page 37: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 37/252

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

37

ArraysMagnitude, 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 theabsolute 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, double-click on the variable youwant to open.

22

2

2

1 n x x x

MATLAB : Chapter 2 Numeric Cell and Structure Arrays

Page 38: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 38/252

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

38

Multidimensional ArraysMATLAB supports multidimensional arraysThe 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];

293

085

164

574

130

926

MATLAB : Chapter 2 Numeric Cell and Structure Arrays

Page 39: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 39/252

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Multidimensional Arrays cat command

59

28A

37

64 B C = cat(3, A, B) produces a three-dimensional

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 23 4

C(:,:,2) =5 67 8

>> d = size(c)d =

2 2 2

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 40: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 40/252

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

40

Element-by-Element OperationsElement-by-element operations

Symbol Operation Form Example

+ Scalar-array addition A + b [6, 3] + 2 = [8 ,5]

- Scalar-array 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

Page 41: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 41/252

: p . , , y

Element-by-Element Operations<example1> <example2>

>> x = [ 1 2 3];>> y = [ 4 5 6];>> x.^yans=

1 32 729

>>y.^2ans=

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

Page 42: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 42/252

p , , y

42

Matrix OperationsMatrix 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 2475 1161 116

Special Matrices

Command Description

eye(n) Creates an n × n identity matrix.

eye(size(A)) Creates an identity matrix the same size as the matrix A.

ones(n) Creates an n × n matrix of ones.ones(m,n) Creates an m × n array of ones.

ones(size(A)) Creates an array of ones the same size as the array A.

zeros(n) Creates an n × n matrix of zeros.

zeros(m,n) Creates an m × n 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

Page 43: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 43/252

p y

43

Matrix OperationsMatrix Division

Right and left operators, / and \Chapter 6 covers matrix division and matrix inverse.

Matrix Exponentiationmust be a square matrix

to find A 2, type A^2

Special products

Command Syntax

cross(A, B) Computes a 3 × n array whose columns are the crossproducts of the corresponding columns in the 3 × narrays A and B. Returns a three-element cross-product vector if A and B are three-element vectors.

dot(A, B) Computes a row vector of length n whose elementsare the dot products of the corresponding columnsof the m × n arrays A and B

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 44: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 44/252

44

Polynomial Operations Using Arrays

Type help polyfun for more information

We will use following notation

Polynomial Addition and Subtrctionadd the arrays that describe their coefficientsif the polynomials are of different degrees, add zeros to the coefficient array of theleower-degree 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]

12

12

31

21)( nnnnnn a xa xa xa xa xa x f

7359)(23

x x x x f 26)(2

x x x g )()()( x g x f xh

929)( 23 x x x xh

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 45: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 45/252

45

Polynomial Operations Using ArraysPolynomial 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 isgiven by the coefficient array q, and the remainder polynomial is given by the coefficient arrayr.

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 matrixor a vector. The polynomial‟s coefficients of descending powers are stored in the array a. Theresult is the same size as x.

roots(a) Computes the roots of a polynomial specified by the coefficient array a. The result is a columnvector that contains the polynomial‟s roots.

1429413954

)26)(7359()()(2345

223

x x x x x

x x x x x x g x f

5833.05.126

7359)()(

2

23

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 , Pos tech ATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 46: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 46/252

46

Polynomial Operations Using Arrays

Plotting PolynomialsThe polyval(a,x) function is very useful for poltting polynomials.

<example>plot the polynomial

7359)( 23 x x x x f 52 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

Page 47: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 47/252

47

Cell Arrays

Cell array : an array in which each element is a bin, or cell which can containan array.

• examplesB = [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 = [ H1, 1; H1, 2; H(2, 2 ];

10

53

96 42

27

529

386

842

J

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 48: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 48/252

48

Cell Arrays

Cell array functions

Function Description

C = cell(n) Creates an n × n cell array C of empty matrices.

C = cell(n,m) Creates an n × m 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

Page 49: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 49/252

49

Cell Arrays

Cell Array Function Examples

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 50: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 50/252

50

Structure Arrays

Structure ar rays : composed of s t ructures .enables you to store dissimilar arrays together accessed using namef ie lds

Creat ing St ruc tures using ass ign ment s ta tements

u s ing the s t ruc t func t ion

dot n ota t ion ( .) : to sp ec i fy and to access the f ie lds

<example>

student.name = ‘ John Smith ’ ; student.SSN = ‘ 392-77-1786 ’ ; student.email = ‘ [email protected] ’ ; student.tests = [67, 75, 84];

student(2).name = ‘ Mary Jones ’ ; student(2).SSN = ‘ 431-56-9832 ’ ; student(2).email = ‘ [email protected] ’ ; student(2).tests = [84, 78, 93];

Structure array“

student”

Student(1)

Name: John Smith

SSN: 392-77-1786

Email: [email protected]

Tests: 67, 75, 84

Student(2)

Name: Mary Jones

SSN: 431-56-9832

Email: [email protected]

Tests: 84, 78, 93

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 51: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 51/252

51

Structure Arrays

Structure functions

Function Description

names = fieldnames(S) Returns the field names associated with the structure array S asnames , 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 , and0 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 structurearray S

S = struct(„f1‟, „v1‟, „f2‟, „v2‟, …) Creates a structure array with the fields „f1‟, „f2, … having thevalues „v1‟, „v2‟, ….

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 52: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 52/252

52

Structure ArraysStructure Arrays Examples

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 53: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 53/252

MATLAB

CHAPTER 3Functions and Files

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 54: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 54/252

Elementary Mathematical Functionsl ookfo r : 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

Page 55: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 55/252

Exponential and Logarithmic Functions

Some commonmathematicalfunctions

Exponential

exp(x) Exponential;

sqrt(x) Square root;

Logarithmiclog(x) Natural logarithm; ln x

log10(x) Common(base10)logarithm;log(x) means ln x.

xe x

Complex

abs(x) Absolute value; xangle(x) Angle of a complex number x

conj(x) Complex conjugate

imag(x) Imaginary part of a complexnumber x

real(x) Real part of a complex number xNumeric

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

Page 56: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 56/252

Complex Number Functions(1/2)

rectangular representationa + ib

polar representation

abs (x ), ang le(x ) absolute value (magnitude)angle

conj(x) complex conjugate

θ

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 57: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 57/252

Complex Number Functions(2/2)

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 58: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 58/252

Numeric FunctionsMATLAB has been optimized to deal with arrays.

round(y) : rounds to the nearest integer ans = 2, 3, 4f ix(y) : truncates to the nearest integer toward zero ans = 2, 2, 3ceil(y) : rounds to the nearest integer toward ∞ ans = 3, 3, 4e.g. z = [-2.6 , -2.3 , 5.7]floor(z) : rounds to the nearest integer toward - ∞ ans = -3, -3, 5fix(z) = -2, -2, 5abs(z) = 2.6 , 2.3, 5.7

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 59: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 59/252

Trigonometric Functions

Table 3.1-2Trigonometric 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.

Inversetrigonometric

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) four-quadrantinverse tangent.

xos 1

xo t 1

xsc 1

xec 1

xin 1

xan 1

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 60: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 60/252

Hyperbolic Functions(1/2)

Hyperbolicfunctions

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

)/2ex

)/2e x

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 61: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 61/252

Hyperbolic Functions(2/2)

Hyperbolicfunctions

Inversehyperbolic

acosh (x) Inverse hyperbolic cosine;acoth (x) Inverse hyperbolic cotangent;

acsch (x) Inverse hyperbolic cosecant;

asech (x) Inverse hyperbolic secant;asinh (x) Inverse hyperbolic sine;

atanh (x) Inverse hyperbolic tangent;

1,n(xosh 2

121

x x,1

1ln(o th or

0x,x1

x1

ln(s c h 21

1 ,x

1

x

1ln(ec h

2

1

x ,n(xinh 2

1 ,x

xln(

2

1xanh 1

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 62: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 62/252

User-Defined Functions(1/4)Funct ion f i l e : when need to repeat a set of commands several times.

variables : localsyntax

function [output variables] = function_name (input variables)function_name = saved file name ( with the .m extension)

function_name = drop : file name = drop.m

e.g.

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 63: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 63/252

User-Defined Functions(2/4)

e.g.

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 64: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 64/252

User-Defined Functions(3/4)

the order of arguments is important, no t the names of thearguments

use arrays as input arguments

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 65: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 65/252

User-Defined Functions(4/4)more than one output

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 66: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 66/252

Variations in the Function Line

Funct io n def ini t ion l ine Fi le name

1. function [area_square] = square(side); square.m

2. function area_square = square(side); square.m

3. function [volume_box] = box(height,width,length); box.m

4. function [area_circle, circumf] = circle(radius); circle.m

5. function sqplot(side); sqplot.m

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 67: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 67/252

Local Variables, Global Variables

Local variablesvariables created by a function file are local to that function.local : their values are not available outside the function.

Global variablestheir values are available to the basic workspace and to other functions that declare these variables global.

variables in script file : global

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 68: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 68/252

Minimization and root-finding functionsTable 3.2-1 Minimization and root-finding functions

Function Descriptionfminbnd(„function‟,x1

,x2)

Returns a value of x in the interval x1 ≤x ≤x2

that corresponds to a minimum of the single-variable function described by the string‘function’.

fminsearch(„function‟,x0)

Uses the starting vector x0 to find a minimumof the multivariable function described by the

string ‘function’ .fzero(„function‟,x0) Uses the starting value x0 to find a zero of

the single-variable function described by thestring ‘function’ .

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 69: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 69/252

Advanced Function Programming

Function Handlesusing the at sign : @

e.g.

>> sine_handle = @ sin;

>> plot([0:0.01:6], sine_handle(0: 0.01: 6))function x=gen_plot(fun_handle, interval)plot(interval, fun_handle, interval)

>>gen_plot(sine_handle, [0: 0.01: 6]) or >>gen_plot(@sin, [0: 0.01: 6])

advantagesspeed of execution and providing access to subfunctions.a standard MATLAB data type, and thus can be used in thesame manner as other data types.

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 70: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 70/252

Methods for Calling Functionsfour ways to invoke, or “call,” a function into action.

1. As a character string identifying the appropriate function M-file.function y = fun1(x)y = x.^2-4;

>>[x, value] = fzero(„fun1‟,[0,3]) 2. As a function handle.

>>[x, value] = fzero(@fun1,[0,3])3. As an “inline” function object, or

>>fun1 = „x.^2 -4‟; >>fun_inline = inline(fun1);>>[x, value] = fzero(fun_inline, [0,3])

4. As a string expression.>>fun1 = „x.^2 -4‟; >>[x, value] = fzero(fun1, [0,3]) or as>>[x, value] = fzero(„x.^2 -4‟, [0,3])

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 71: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 71/252

Types of Functions(1/2)

primary functionscontains the main program.the only function that you can call from the MATLAB command line or fromanother M-file function

anonymous functionscreate a simple function without needing to create an M-file for it.

provide a quick way of making a function from any MATLAB expression

subfunctionsplaced in the primary functionuse multiple functions within a single primary function M-file

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 72: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 72/252

Types of Functions(2/2)

nested functionsdefined within another functionhelp to improve the readability of your program

difference between nested functions and subfuntions: subfunctions normallycannot be accessed outside of their primary function fle

overloaded functionsfunctions that respond differently to different types of input arguments.created to treat integer inputs differently than inputs of class double.

private functionsrestrict access to a functioncalled only from an M-file function in the parent directory

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 73: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 73/252

Anonymous Functionscreate a simple function without needing to create an M-filefor it.

MATLAB command linefrom within another function or script

syntaxfhan dle = @(arglis t) expr

arglist: a comma-separated list of input arguments to be passed to thefunctionexpr: any single, valid MATLAB expressione.g.

sq = @(x) x.^2;

>>sq(5)>>sq([5,7])

be useful for more complicated functions involvingnumerous keystrokes.

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 74: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 74/252

Variables and Anonymous Functions

variables can appear in anonymousfunctions in two ways

as variables specified in the argument liste.g.

f = @(x) x.^3;

as variables specified in the body of the expressione.g.

plane = @(x, y) A*x + B *y;

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 75: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 75/252

Subfunctions(1/2)

all other functions in the pr imary function are called sub func t i ons .

the order for checking functions inMATLAB

1. checks to see if the function is a built-in function such s sin.2. checks to see if the function is subfunction in the file.3. checks to see if the function is private function.

may use subfunctions with the samename as another existing M-file.

allow you to name subfunctions without being concerned about whether another function exists with the same nameprotects you from using another function unintentionally

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 76: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 76/252

Subfunctions(2/2)

e.g.function y = subfun_demo(a)y = a – mean(a);

%function w = mean(x)w = sqrt(sum(x.^2))/length(x);a sample session follows.>> y =subfun_demo([4,-4])y =

1.1716 -6.8284if had used the MATLAB M-function mean different answer

>> a= [4, -4];>> b =a – mean(a)b =

4 -4

primary function

subfunction

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 77: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 77/252

Nested Functions(1/2)

Functions that are defined within the main function.contains the usual components of an M-file function.must always terminate with an en d statement.

e.g.function f = parabola(a, b, c)f =@p;

function y = p(x)y = a*x^2 + b*x + c;

endendIn the command window type>>f = parabola(4, -50, 5);>>fminbnd(f, -10, 10)ans =

6.2500

6.2500

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 78: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 78/252

Nested Functions(2/2)

two unique properties1. can access the workspace of all functions inside of which it is nested.2. function handle

stores the information needed to access the nested functionstores the values of all variables shared between the nested function andthose functions that contain it

call a nested function1. from the level immediately above it2. from a function nested at the same level within the same parent function3. from a function at any lower level

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 79: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 79/252

Private Functions

reside in subdirectories with the

special name pr ivate .visible only to functions in the parentdirectory.

invisible outside the parent directory.MATLAB looks for private functionsbefore standard M-file functions.

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

W ki g ith D t Fil

Page 80: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 80/252

Working with Data Files

header : a comment that describe whatthe data represent, the date it wascreated, and who created the date.Im po r t ing da ta : bring data created byother applications into the MATLABworkspace.Expor t ing da ta : package workspace

variables so that they can be used byother applications.Im po r t ing Wizard : a graphical user

interface

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 81: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 81/252

Using Import Functions with Text Data

• To import text data from the command line or in an M-file, choice of functiondepends on how the data in the text file is formatted.

• The text data must be formatted in a uniform pattern of rows and columns, using atext character, called a delimiter or column separator, to separate each data item.

•The delimiter can be a space, comma, semicolon, tab, or any other character. Theindividual data items can be alphabetic or numeric characters or a mix of both.

• The text file can also contain one or more lines of text, called header lines, or canuse text headers to label each column or row.

•To find out how the data is formatted, view it in a text editor. After determine theformat, find the sample in the table that most closely resembles the format of data.

•Then read the topic referred to in the table for information on how to import thatformat.

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

T bl 6 1 ASCII D Fil F

Page 82: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 82/252

Data Format Sample File Extension

Description

1 2 3 4 56 7 8 9 10

.txt.dat or other

See Importing Numeric Text Data or Using the Import Wizard with Text Data for information.

1; 2; 3; 4; 56; 7; 8; 9; 10or

1, 2, 3, 4, 56, 7, 8, 9, 10

.txt

.dat

.csv

or other

See Importing Delimited ASCII Data Files or Using the Import Wizard with Text Data for information.

Ann Type1 12.34 45 YesJoe Type2 45.67 67 No

.txt

.dator other

See Importing Numeric Data with Text Headersfor information.

Grade1 Grade2 Grade391.5 89.2 77.388.0 67.8 91.067.3 78.1 92.5.

txt.dator other

• See Importing Numeric Data with Text Headersor Using the Import Wizard with Text Data for information.

If you are familiar with MATLAB import functions but are not sure when to use them,

see the following table, which compares the features of each function.

Table 6-1: ASCII Data File Formats

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

T bl 6 2 ASCII D I F i F

Page 83: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 83/252

Function Data Type Delimiters

Number of Return Val

ues

Notes

Csvread Numeric data Commasonly

One Primarily used with spreadsheet data.See Working with Spreadsheets.

Dlmread Numeric data Anycharacter

One Flexible and easy to use.

Fscanf Alphabetic and num

eric; however, both types returned in a single return variable

Any

character

One Part of low-level file I/O routines. Requi

res use of fopen to obtain file identifier and fclose after read.

load Numeric data Spaces only

One Easy to use. Use the functional form of load to specify the name of the output variable.

textread Alphabetic and numeric

Anycharacter

Multiple values in cell arrays

Flexible, powerful, and easy to use. Use format string to specify conversions

textscan Alphabetic and numeric

Any character

Multiple values returned to one cellarray

More flexible than textread. Also more f ormat options

Table 6-2: ASCII Data Import Function Features

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 84: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 84/252

MATLAB

CHAPTER 4Programming with MATLAB

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 85: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 85/252

OUTLINEProgram Design and DevelopmentRelational Operators and Logical VariablesLogical Operators and Functions

Conditional StatementsLoopsThe „switch‟ structure

Input and OutputDebugging MATLAB ProgramsSummary

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Program design and development(1/3)

Page 86: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 86/252

Program design and development(1/3)Algo r i thm s and co n t ro l s t ruc tu res

Sequential operationsConditional operationsInterative operations (loops)

Struc tu red p rog ram m ing Table 4.1-1 Steps for developing a computer solution1. State the problem concisely

2. Specify the data to be used by the program. This is the “input.” 3. Specify the information to be generated by the program, this is the “output.”

4. Work through the solution steps by hand or with a calculator; use a simpler set of data if necessary

5. Write and run the program

6. Check the output of the program with your hand solution

7. Run the program with your input data and perform a reality check on theoutput

8. If you will use the program as a general tool in the future, test is by runningit for a range of reasonable data values; perform a reality check on theresults

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Program design and development(2/3)

Page 87: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 87/252

Program design and development(2/3)

St ruc tu re char t & F low ch art

P s e d o c o d e Examp le 1 . sequent ia l op erat ions

p=a+b+c

a= inp ut ( ˙ Enter the value of s id e a: );

b= inpu t ( ˙ Enter the value of s ide b : );

c= inpu t ( ˙ Enter the value of s ide c : );

p=a+b+c;

s=p/2; A=sqrt(s*(s-a)*(s-b)*(s-c));

disp(˙ The perimeter is: ˙ )

p

disp(˙ The area is: ˙ )

A

))()(( c sb sa s s A2 p

s

Example 2 . co ndi t ion al op erat ions

x=input( ˙ Enter the va lue of s ide x : ); y=input ( ˙ Enter the va lue of s ide y : ); r=sqr t (x^2+y^2) ; If x >=0

theta=atan(y/x); else

theta=atan(y/x)+pi; en d

d i sp (˙ The hypoteneuse is: ˙ ) disp(r ) theta=theta*(180/pi); d i sp (˙ The angle is degrees is: ˙ ) disp(theta)

22 y xr )(tan 1

x y

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

P d i d d l (3/3)

Page 88: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 88/252

Program design and development(3/3)

Examp le 3 . i te rat ive o pera t ions

Determine how many terms arerequired for the sum of the series10k 2 -4k+2 , k=1,2,3,… to exceed 20,000

Tot al = 0; K = 0; Wh ile total < 2e+4

k = k +1;

Total = 10*k^ 2 – 4*k +2 + to tal; en d disp ( ‘ The number of terms is : ‘ ) d i sp ( k ) disp ( ‘ The sum is : ‘ ) d isp ( to ta l )

Total > 20,000 ?

Total = 0k = 0

Total =10k 2 -4k+2

k = k + 1

START

END

DISP k, Total

True

False

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 89: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 89/252

Relational operators and logical variables(1/2)

Table 4.2-1 Relat ion al o perators

Relationaloperator

Meaning

< Less than

<= Less than or equalto

> Greater than

>= Greater than or

equal to== Equal to

~= Not equal to

Example

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

R l i l d l i l i bl (2/2)

Page 90: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 90/252

Relational operators and logical variables(2/2)

The logical class

example

The logica l funct ion

example

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 91: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 91/252

Logical operators and functions(1/6)

Tab le 4.3-1 log ical o p erators Operator Name Definition

~ NOT ~A returns an array the same dimension as A; the newarray has ones where A is zero and zeros where A isnonzero.

& AND A&B returns an array the same dimension as A and B;the new array has ones where both A and B havenonzero elements and zeros where either A or B is zero.

| OR A|B returns an array the same dimension as A and B; thenew array has ones where at least one element in A or Bis nonzero and zeros where A and B are both zero.

&& Short-CircuitAND

Operator for scalar logical expressions. A && B returnstrue if both A and B evaluate to true, and false if they donot.

|| Short-CircuitOR

Operator for scalar logical expressions. A || B returnstrue if either A or B or both evaluate to true, and false if they do not.

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 92: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 92/252

Logical operators and functions(2/6)

Example 1. Not

2. An d

3. Or

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 93: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 93/252

Logical operators and functions(3/6)

Table 4.3-2 order of preced ence for op erator typ es

Precedence Operator type

First Parentheses „ () „; evaluated starting with theinnermost pair.

Second Arithmetic operators and logical NOT(~); evaluatedfrom 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)

Page 94: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 94/252

Logical operators and functions(4/6)

x y ~x x|y 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

Tabl e 4.3-3 Tru th tab le

example

Shor t -c i rcu i t op erators A && B Returns true (logical 1) if both A and B evaluate to true, and false (logical 0) if they donot.

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)

Page 95: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 95/252

Table 4.3-4 logic al func tion s 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 onwhether 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 Aand 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 zeroselsewhere.

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)

Page 96: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 96/252

Logical operators and functions(6/6)Logical operators and the f ind 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)

Page 97: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 97/252

Conditional statements(1/5)

the i f statement

The i f statement‟s basic form is

i f logical expressionstatements

en d

the nested i f statement

i f logical expression 1statements group 1i f logical expression 2

statement group 2en d

en d

Start

LogicalExpression 1

StatementGroup 1

True

False

FalseLogicalExpression 2

StatementGroup 2

Statement

Group 3

True

End

Figure 4.4-3 flowchart for

the general if structure

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Conditional statements(2/5)

Page 98: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 98/252

Conditional statements(2/5)Example

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Conditional statements(3/5)

Page 99: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 99/252

Conditional statements(3/5)

the else statement

i f logical expressionstatements group 1

else statements group 2

end

example

Start

StatementGroup2

StatementGroup1

LogicalExpression

False

End

True

Figure 4.4-2 flowchart forthe general else structure

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Conditional statements(4/5)

Page 100: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 100/252

Conditional statements(4/5)

the elseif statement

if logical expressionstatements group 1

elseif logicalexpression2

statements group 2else

statements group 3en d

Checking the number of input andoutput arguments

nargin -number 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

Page 101: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 101/252

Conditional statements(5/5)

Strings and conditional statementsNameNumber findstr Input

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Loops (1/4)

Page 102: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 102/252

Loops (1/4)fo r Loops

fo r loop variable=m:s:nstatements

en d

Example

for k=5:10:35x=k^2

end

Figure 4.5-1 flowchartof a for loop.

Start

Set k = m

Incrementk by s

k > n ?

False

End

True

Statements

Statementsfollowing the

End statement

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Loops (2/4)

Page 103: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 103/252

Loops (2/4)

break – terminates the loopbut does not stop the entire program

example

for k=1:10x=50-k^2;if x<0

breakendy=sqrt(x)

end

Cont inue- passes control to thenext iteration of the for or whileloop in which it appears

example

x=[10,1000,-10,100];y=NaN*x;

for k=1:length(x)if x(k)<0

continueendy(k)=log10(x(k));

endy

The result is y=1,3,NaN,2.

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Loops (3/4)

Page 104: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 104/252

Loops (3/4)Using an array as a loop index

example A=[1,2,3;4,5,6];for v=A

disp(v)end

Imp l ied L oops

Use of logical ar rays as m asks

example

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Loops (4/4)

Page 105: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 105/252

Loops (4/4)whi l e Loops

whi l e loop variable=m:s:nstatements

En d

Example

x=5;while x<25

disp(x)x=2*x-1;

end

1. The loop variable must have a valuebefore the while statement is executed.

2. The loop variable must be changedsomehow by the statements.

Figure 4.5-3 flowchartof the while loop.

Statementsfollowing the

End statement

End

Start

LogicalExpression

True

False

Statements(which incrementthe loop variable)

MATLAB : Chapter 2. Numeric, Cell, and Structure Arrays

Page 106: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 106/252

The swi tch structure

sw i tch inp u t express ion (sca lar o r s t r ing)

case value 1statement group 1

case value 2statement group 2

.

.

.

Otherwisestatement group n

end

example

switch anglecase 45

disp(„Northeast‟)

case 135disp(„Southeast‟)

case 225disp(„Southwest‟)

case 315disp(„Northwest‟)

otherwisedisp(„Direction Unknown‟)

end

Page 107: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 107/252

107

MATLAB

CHAPTER 5Advanced Plotting and Model Building

MATLAB : Chapter 5. Advanced Plotting and Model Building

Page 108: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 108/252

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

TICK-MARK LABEL

AXIS LABEL

DATA SYMBOL

PLOT TITLE

The Anatomy of a Plot

SPaC, Postech ATLAB : Chapter 5. Advanced Plotting and Model Building

Page 109: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 109/252

109

xy Plotting Functions

Requirements for a Correct Plot1. 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 alegend to distinguish them.

4. If you are preparing multiple plots of similar type or if the axes‟ labels cannotconvey 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 thedata points, especially with a solid line.

7. If you are plotting points generated by evaluating a function, do not use a symbolto plot the points. Instead, be sure to generate many points, and connect thepoints with solid lines.

MATLAB : Chapter 5. Advanced Plotting and Model Building

Page 110: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 110/252

110

xy Plotting Functions

Plot, Label, and Title Commandsxlabel and ylabel commands put labelson the abscissa and the ordinate.title command puts a title at the top of theplot.

<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 ATLAB : Chapter 5. Advanced Plotting and Model Building

Page 111: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 111/252

111

xy Plotting Functions

grid and axis Commandsgrid : 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 ATLAB : Chapter 5. Advanced Plotting and Model Building

Page 112: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 112/252

112

xy Plotting Functions

Plots of Complex Numbersplot (y) : Plots the imaginary parts of y versus the real parts if y is a vector having

complex values.

SPaC, Postech ATLAB : Chapter 5. Advanced Plotting and Model Building

xy Plotting Functions

Page 113: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 113/252

113

y gThe Function Plot Command fplot

fplot : automatically analyzes the function to be plotted and decideshow many plotting points to use so that the plot will show all thefeatures of the function.Basic syntax: fplot ( „string‟ , [xmin xmax] )

where „string‟ is a text string that describes the function to be plottedand [xmin xmax] specifies the minimum and maximum values of the independent variable.

SPaC, Postech ATLAB : Chapter 5. Advanced Plotting and Model Building

xy Plotting Functions

Page 114: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 114/252

114

xy Plotting Functions

Plotting PolynomialsWe 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

907210023)( 2345 x x x x x x f )66( x

SPaC, Postech ATLAB : Chapter 5. Advanced Plotting and Model Building

Subplots and Overlay Plots

Page 115: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 115/252

115

Subplots and Overlay PlotsBasic xy plotting commands

Command Description

axis([xmin, xmax yminymax])fplot(„string‟, [xmin xmax])

Gridplot(x,y)plot(y)

print title („text‟) xlabel („text‟) ylabel („text‟)

Sets the minimum and maximum limits of the x- and y-axes.Performs intelligent plotting of functions, where „string‟ is atext string that described the function to be plotted and[xmin xmax] specifies the minimum and maximum valuesof the independent variable. The range of the dependentvariable can also be specified. In this case the syntax isfplot(„string‟, [xmin xmax ymin ymax]).Display gridlines at the tick marks corresponding to thetick labels.Generates a plot of the array y versus the array x onrectilinear 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 avector 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 x-axis(the abscissa).Adds a text label to the y-axis(the ordinate).

MATLAB : Chapter 5. Advanced Plotting and Model Building

Subplots and Overlay Plots

Page 116: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 116/252

116

p ySubplots

Basic syntax: subplot (m, n, p)<example1> subplot (3, 2, 5) : This command creates an array of six pane, three panes deep and twopanes across, and directs the next plot to appear in the fifth pane (in the bottom-left 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.^3-100);

subplot(1,2,2)

plot(x,y),xlabel('x'),ylabel('y'),…

axis([-6 6 0 350])

MATLAB : Chapter 5. Advanced Plotting and Model Building

Subplots and Overlay Plots

Page 117: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 117/252

117

p yOverlay 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) xCircle (o) oPlus sign (+) +Square ( ) s

Diamond ( ◊ ) dFive-pointed star ( ) p

Solid line -Dashed line - -Dash-dotted line -.Dotted line :

Black kBlue bCyan cGreen gMagenta mRed r

White w Yellow y

SPaC, Postech ATLAB : Chapter 5. Advanced Plotting and Model Building

Subplots and Overlay Plots

Page 118: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 118/252

118

p yData Markers and Line Types

plot(x,y,'*',x,y,':‘)

plot(x,y,x,y,'o‘)

plot(x,y,'o‘)

SPaC, Postech ATLAB : Chapter 5. Advanced Plotting and Model Building

Subplots and Overlay Plots

Page 119: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 119/252

119

Labeling Curves and Datalegend 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 ATLAB : Chapter 5. Advanced Plotting and Model Building

Subplots and Overlay Plots

Page 120: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 120/252

120

The hold Commandhold command create a plot that needs two or more plotcommands.be useful with some of the advanced MATLAB toolboxcommands 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 ATLAB : Chapter 5. Advanced Plotting and Model Building

Page 121: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 121/252

121

Subplots and Overlay PlotsPlot enhancement commands

Command Description

axesgtext („text‟)

holdlegend („leg1‟, ‟leg2‟, …)

plot (x, y, u, v)plot (x, y, „type‟)

plot (A)

plot (P, Q)

refreshsubplot (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 itsplacement 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 ncurves.Plots array Q versus array P. See the text for a description of the possiblevariants 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 ncolumns and directs the subsequent plotting commands to the p-thsubwindow.Places the string text in the Figure window at a point specified bycoordinates x, y.

MATLAB : Chapter 5. Advanced Plotting and Model Building

Subplots and Overlay Plots

Page 122: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 122/252

122

p yAnnotating 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 tick-mark 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

Special Plot Types

Page 123: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 123/252

123

Logarithmic plotslog-log plot: log scales on both axes.

semilog plot: a log scale on only one axis.

MATLAB : Chapter 5. Advanced Plotting and Model Building

Special Plot Types

Page 124: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 124/252

124

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 log-log plot of y versus x.

Produces a plot with two y-axes, y1 on the left and y2 onthe right.

Produces a polar plot from the polar coordinates thetaand r, using the line type, data marker, and colorsspecified in the string type.

Produces a semilog plot of y versus x with logarithmicabscissa scale.

Produces a semilog plot of x versus y with logarithmicabscissa scale.

Produces a stairs plot of y versus x.

Produces a stem plot of y versus x.

SPaC, Postech ATLAB : Chapter 5. Advanced Plotting and Model Building

Special Plot Types

Page 125: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 125/252

125

Frequency-Response Plots and Filter Circuits

<example> Frequency-Response Plot of a Low-Pass Filter

, where s = ω i and RC = 0.1 second1

1 RCs A

A

i

o

R

C

+

-vi vo

100

101

102

10-1

100

Frequency (rad/s)

O u

t p u

t / I n p u

t R a

t i o

Frequency Response of a Low-Pass RC Circuit (RC = 0.1 s)

MATLAB : Chapter 5. Advanced Plotting and Model Building

Th Di i l Pl

Page 127: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 127/252

MATLAB

CHAPTER 6Numerical calculus and differential equations

MATLAB : Chapter 8. Numerical calculus and differential equations

OUTLINE

Page 128: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 128/252

OUTLINE

Numerical integrationI(2)

Numerical differentiation(3)

Numerical Methods for Differential Equations(7)

Extension to Higher-Order 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)

Page 129: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 129/252

Rectangular integration trapezoidal integration

Numerical integration functions

Command Description

quad („function‟,a,b,tol) Uses an adaptive Simpson‟s rule to compute the integral of the function

‘function ’ with a as the lower integration limit and b as the upper limit. Theparameter 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’. Therest 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

xa b

y=f(x) y=f(x)

y

xa b··· ···

0sin dx

2cos0coscossin00

xdx

(exact solution)

(use of the trapzfunction)

MATLAB : Chapter 8. Numerical calculus and differential equations

Numerical integrationI(2/2)

Page 130: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 130/252

Quadratu re func t ions

quad („function‟,a,b)

quadl („function‟,a,b)

Slope func t ion s ingu la ri t i es

example

xdxdy

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 tointegrate discretized data (onlypossible for fixed to function)

MATLAB : Chapter 8. Numerical calculus and differential equations

Numerical differentiation(1/3)

Page 131: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 131/252

x y y

x x y y

m B

23

23

23

x1 x2 x3

y1

y2

y3

Δ x Δ x

y=f(x)

True slope

A

B

C

x y y

x y y

x y ymm

mB A

C

221

2132312

x

y y

x x

y ym A

12

12

12

x y

dxdy

limΔx 0

: backward difference

: central difference

: forward difference

: Difinition

MATLAB : Chapter 8. Numerical calculus and differential equations

Numerical differentiation(2/3)

Page 132: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 132/252

The d i ff Func t ion

d= di ff (x) ->( d=[x(2)-x(1),x(3)- x(2), … ] )

Backward difference & centraldifference 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)

Page 133: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 133/252

b = polyder (p)p = [a 1,a 2,…,a n]b = [b 1,b 2,…,b n-1 ]b = polyder (p1,p2)[num, den] = polyder(p2,p1)

nnnnn a xa xa xa xa x f 1

23

121)(

12

21

1 )1( nnn a xan xna

dxdf

12

21

1 nnn b xb xb

Example p1= 5x +2

p2=10x 2+4x-3

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 representedby the vector p .

b=polyder(p1,p2) Returns a vector b containing the coefficients of the polynomial that is the derivative of theproduct 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 d en containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p 2 /p 1, where p1 and p 2 are polynomials.

Numerical differentiation functions

po lyno m ial Derivat ives

MATLAB : Chapter 8. Numerical calculus and differential equations

Numerical Methods for Differential Equations(1/7)

Page 134: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 134/252

Runge-Kutta MethodsThe second-order Runge-Kutta methods:

(8.5-17) , where : constant weighting factors

(8.5-18)(8.5-19)

To duplicate the Taylor series through the h 2 term, these coefficientsmust satisfy the following:

(8.5-19)

(8.5-19)

(8.5-19)

22111 g w g w y y k k

),(

),(

2

1

k k k

k k

hf yht hf g

yt hf g

21, ww

2

12

1

1

2

1

21

w

w

ww

MATLAB : Chapter 8. Numerical calculus and differential equations

Numerical Methods for Differential Equations(2/7)

Page 135: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 135/252

The fourth-order Runge-Kutta methods:

(8.5-23)

(8.5-24)

443322111 g w g w g w g w y y k k

])(,[

])(,[

),(

),(

1333332334

1222223

112

1

g g g yht hf g

g g yht hf g

g yht hf g

yt hf g

k k

k k

k k

k k

0

1

21

21

31

61

3

33

2

21

32

41

ww

ww

MATLAB : Chapter 8. Numerical calculus and differential equations

Numerical Methods for Differential Equations(3/7)

Page 136: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 136/252

MATLAB ODE Solvers ode23 and ode45MATLAB provides functions, called solvers , that implement Runge-Kutta

methods with variable step size.The ode23 function uses a combination of second- and third-order Runge-Kutta methods, whereas ode45 uses a combination of fourth- and fifth-order methods.

<Table 8.5-1> ODE solvers

Solver name Description

ode23 Nonstiff, low-order solver.ode45 Nonstiff, medium-order solver.ode113 Nonstiff, variable-order solver.

ode23s Stiff, low-order solver.ode23t Moderately stiff, trapezoidal-rule solver.ode23tb Stiff, low-order solver.ode15s Stiff, variable-order solver.

MATLAB : Chapter 8. Numerical calculus and differential equations

Numerical Methods for Differential Equations(4/7)

Page 137: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 137/252

Solver Syntax

<Table 8.5-2> Basic syntax of ODE solvers Command Description

[t, y] = ode23 ( „ydot‟, tspan, y0) Solves the vector differential equation specifiedin function file ydot, whose inputs must be t and y andwhose output must be a column vector representing; that is, . The number of rows in this columnvector must equal the order of the equation. The vector tspan contains the starting and ending values of theindependent variable t, and optionally, any intermediatevalues of t where the solution is desired. The vector y0contains. The function file must have two inputarguments t and y even for equations where is nota function of t. The syntax is identical for the other solvers.

),(.

yt f y

dt dy

),(.

yt f y

)( 0t y

),( yt f

Page 138: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 138/252

MATLAB : Chapter 8. Numerical calculus and differential equations

Numerical Methods for Differential Equations(6/7)

Page 139: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 139/252

Effect of Step Size

The spacing used by ode23 is smaller than that used by ode45 becauseode45 has less truncation error than ode23 and thus can use a larger stepsize.ode23 is sometimes more useful for plotting the solution because it oftengives a smoother curve.

Numerical Methods and Linear EquationsIt is sometimes more convenient to use a numerical method to find thesolution.Examples of such situations are when the forcing function is a complicatedfunction or when the order of the differential equation is higher than two.

Use of Global ParametersThe global x y z command allows all functions and files using that command to sharethe values of the variables x, y, and z.

MATLAB : Chapter 8. Numerical calculus and differential equations

Numerical Methods for Differential Equations(7/7)

Page 140: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 140/252

Use of Global Parameters( Example ) The circuit‟s 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 ydt

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 Higher-Order Equations(1/6)h h f h bl f

Page 141: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 141/252

The Cauchy form or the state-variable formConsider the second-order equation

(8.6-1)

(8.6-2)

If , , then

5 7 4 ( ) y y y f t 1 4 7

( )5 5 5

y f t y y

y x1

2 x y

21

.

2

2

.

1

57

54

)(51

x xt f x

x xThe Cauchy form

or state-variable form

MATLAB : Chapter 8. Numerical calculus and differential equations

Extension to Higher-Order Equations(2/6).

Page 142: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 142/252

<example> Solve (8.6-1) for with the initial conditions .

( Suppose that and use ode45 .)60 t 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 in i t ial condi t ion for

the vec tor 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 Higher-Order Equations(3/6)

Page 143: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 143/252

Matrix Methods

< a mass and spring with viscous surface friction > y

f(t)m

k

c

)(...

t f ky yc ym

21

. x x

212 )(1. xmc x

mk t f

m x

( Letting , ) y x1

.2 y x

)(1010

2

1

2

1..

t f m x

x

mc

mk

x

x

(Matrix form)

)(

.t f

mc

mk

10

m10

2

1

x

x

(Compact form)

(8.6-6)

(8.6-7)

MATLAB : Chapter 8. Numerical calculus and differential equations

Extension to Higher-Order Equations(4/6)

Page 144: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 144/252

Characteristic Roots from the eig Function

Substituting ,

Cancel the terms

Its roots are s = -6.7321 and s = -3.2679.

211 3.

x x x212 7

. x x x

(8.6-8)

(8.6-8)

st st st

st st st

e Ae Ae sA

e Ae Ae sA

212

211

7

3

st e At x 11 )( st e At x 22 )(

st e

0)7(

0)3(

21

21

A s A

A A s 02210

71

13 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 Higher-Order Equations(5/6)

Page 145: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 145/252

MATLAB provides the eig function to compute the characteristic roots.Its syntax is eig(A)

<example> The matrix A for the equations (8.6-8) and (8.6-9) is

To find the time constants, which are the negative reciprocals of thereal parts of the roots, you type tau = -1./real (r). The time constantsare 0.1485 and 0.3060.

7113

MATLAB : Chapter 8. Numerical calculus and differential equations

Extension to Higher-Order Equations(6/6)

Page 146: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 146/252

Programming Detailed Forcing Functions< An armature-controlled dc motor>

v

R L

I

+

-

w K e

i K T T w

cwi

cwi K dt dw

I

t vw K Ridt 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

Apply Kirchhoff‟s voltage law and Newton‟s law

(8.6-10)

(8.6-11)

( matrix form )

: motor‟s current , : rotational velocity i w

L: inductance, R: resistance, I: inertia, : torque constant, : back emf constant,

c: viscous damping constant, : applied voltage

T K e K

)(t v

Letting w xi x 21 ,

MATLAB : Chapter 8. Numerical calculus and differential equations

ODE Solvers in the Control System Toolbox(1/7)

Page 147: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 147/252

Model FormsThe reduced form

The state-model of the same system

)(532 ... t f x x x (8.7-1)

2

1

210

23

25

10

.

x

x

u

(8.7-5)

(8.7-3)

(8.7-4)

(8.7-2)

Both model forms contain the sameinformation. However, each formhas its own advantages, dependingon the purpose of the analysis .

The specification of theoutput:

DuC y

MATLAB : Chapter 8. Numerical calculus and differential equations

ODE Solvers in the Control System Toolbox(2/7)< Table 8 7 1> LTI object functions

Page 148: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 148/252

< Table 8.7-1> LTI object functions

Command Description

sys = ss (A, B, C, D) Creates an LTI object in state-space form, where thematrices A, B, C, and D correspond to those in themodel .

[A, B, C, D] = ssdata (sys) Extracts the matrices A, B, C, and D corresponding tothose in the model

.

sys = tf (right, left) Creates an LTI object in transfer-function form, wherethe 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 left-hand side of the equation, also arranged indescending derivative order.

[right, left] = tfdata (sys) Extracts the coefficients on the right- and left-handsides of the reduced-form model.

DuC yu,.

DuC yu,.

MATLAB : Chapter 8. Numerical calculus and differential equations

ODE Solvers in the Control System Toolbox(3/7)

Page 149: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 149/252

Example

MATLAB : Chapter 8. Numerical calculus and differential equations

ODE Solvers in the Control System Toolbox(4/7)ODE Solvers

Page 150: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 150/252

ODE Solvers<Table 8.7-2> Basic syntax of the LTI ODE solvers

LTI Viewers : It provides an interactive user interface that allows you toswitch between different types of response plots and between the analysisof different systems. The viewer is invoked by typing ltiview.

Command Description

Impulse (sys) Computes and plots the unit-impulse response of the LTIobject sys.

Initial (sys, x0) Computes and plots the free response of the LTI object sys

given in state-model form, for the initial conditions specified inthe vector x0.

lsim (sys, u, t) Computes and plots the response of the LTI object sys to theinput specified by the vector u, at the times specified by thevector t.

step (sys) Computes and plots the unit-step response of the LTI objectsys.

Page 151: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 151/252

Page 152: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 152/252

MATLAB : Chapter 8. Numerical calculus and differential equations

ODE Solvers in the Control System Toolbox(7/7)

Page 153: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 153/252

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 8 1 > Complete syntax of ODE solvers

Page 154: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 154/252

< Table 8.8-1 > Complete syntax of ODE solversCommand 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 mustequal the order of the equation. The vector tspan contains the starting andending values of the independent variable t, and optionally, any intermediatevalues of t where the solution is desired. The vector y0 contains y(t 0). Thefunction file must have two input arguments t and y even for equations wheref(t,y) is not a function of t.The options argument is created with the odeset function, and p1, p2, … areoptional parameters that can be passed to the function file ydot every time it iscalled. If these optional parameters are used, but no options are set, useoptions = [ ] 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 thatthe solver is expecting a specific kind of information. The syntax for all thesolvers 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 thename of a property and value is the value to be assigned to the property. Anyunspecified properties have default values. odeset with no input argumentsdisplays all property names and their possible values.

),(.

yt f y

MATLAB : Chapter 8. Numerical calculus and differential equations

Advanced Solver Syntax(2/2)

Page 155: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 155/252

Stiff Differential Equations

A stiff differential equation is one whose response changes rapidly over atime scale that is short compared to the time scale over which we areinterested 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 alarge error might accumulate.

The four solvers specifically designed to handle stiff equations: ode15s (avariable-order method), ode23s (a low-order method), ode23tb (another low-order method), ode23t (a trapezoidal method).

Page 156: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 156/252

SPaC, POSTECH 156

MATLAB

CHAPTER 7Simulink

MATLAB : Chapter 9. Simulink

Simulation Diagram

Page 157: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 157/252

157

Simulation diagram (block diagram)Consider the equation

Simulation diagrams for

)(10. t f y

dt t f t y )(10)(

)(10)( t f t xdt t xt y )()(

10f(t) y(t)x(t) f yx

10 s1

)(10.

t f y

MATLAB : Chapter 9. Simulink

Introduction to Simulink

Page 158: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 158/252

158

Type Simulink

in the MATLABCommand windowto start window.

The Simulink Library Browser

Type „simulink‟ In the Command

Window

MATLAB : Chapter 9. Simulink

Introduction to Simulink

Page 159: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 159/252

159

Create a new modelClick on the icon that resembles aclean sheet of paper, or select Newfrom the File menu in the Browser.

Click

this iconFile New

Or

MATLAB : Chapter 9. Simulink

Introduction to Simulink

Page 160: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 160/252

160

① Double-click 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, andrelease

MATLAB : Chapter 9. Simulink

Introduction to Simulink

Page 161: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 161/252

161

⑥ 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

Introduction to Simulink

Page 162: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 162/252

162

ExampleSimulink 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

)cos1(10)( t t y

MATLAB : Chapter 9. Simulink

Introduction to Simulink

Page 163: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 163/252

163

① Start Simulink and open a new model window.② Select and place the Sine Wave block from the Source library .

MATLAB : Chapter 9. Simulink

Introduction to Simulink

Page 164: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 164/252

164

③ Double-click to open the Block Parameterswindow .Make sure that Amplitude= 1, Frequency= 1,Phase= 0, Sample time= 0Then click OK .

MATLAB : Chapter 9. Simulink

Introduction to Simulink

Page 165: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 165/252

165

④ 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

Introduction to Simulink

Page 166: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 166/252

166

⑥ Select and place the Scope block from the Sinks library .

⑦ Connect each input and output port.

MATLAB : Chapter 9. Simulink

Introduction to Simulink

Page 167: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 167/252

167

⑧ 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

Introduction to Simulink

Page 168: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 168/252

168

⑨ Run the simulation by clicking on the Simulation menu,and clicking the Start item.

OR

MATLAB : Chapter 9. Simulink

Introduction to Simulink

Page 169: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 169/252

169

⑩ After the simulation, double-click on the Scope block .

Double-click!

MATLAB : Chapter 9. Simulink

Linear State-Variable Models

Page 170: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 170/252

170

State-variable models can havemore than one input and morethan on output.Simulink has the State-spaceblock that represents the linear state-variable model

DuCx y Bu Ax x ,.

MATLAB : Chapter 9. Simulink

Linear State-Variable Models

Page 171: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 171/252

171

ExampleSimulink Model of the Two-Mass System

m1=5, m2=3, c1=4, c2=8, k1=1, and k2=4The equations of motion are

These equations can be expressed in state-variableform as

)(48483

0485125

11222

22111

....

....

t f x x x x x

x x x x x

43

21

.

.

z z

z z

)4(31.

)5(51.

)(848

8412

43214

43212

t f z z z z z

z z z z z

MATLAB : Chapter 9. Simulink

Linear State-Variable Models

Page 172: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 172/252

172

Vector matrix form

)(.

t Bf Az z

A =

0 1 0 0

-1 -12/5 4/5 8/50 0 0 14/3 8/3 -4/3 -8/3

0

00

1/3

B =

2

2

1

1

.

.

x

x

x

xz1

z2z3

z4

z = =

MATLAB : Chapter 9. Simulink

Linear State-Variable Models

Page 173: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 173/252

173

Initinal conditions

Output equation

)(: t Df Cz youtput

1 0 0 0

0 0 1 0C =

0

0D =

0)0(2,5.0)0(2,0)0(1,2.0)0(1..x x x x

Page 174: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 174/252

MATLAB : Chapter 9. Simulink

Linear State-Variable Models

Page 175: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 175/252

175

③Select and place the State-Spacelock . Enter A,B,C,D. Then enter initial condition.

0.2; 0; 0.5; 0

MATLAB : Chapter 9. Simulink

Linear State-Variable Models

Page 176: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 176/252

176

④Select and place the Scope block.

⑤connect each port.

MATLAB : Chapter 9. Simulink

Linear State-Variable Models⑥experiment with different values of the Stop time until the Scope shows thath d h b h d

Page 177: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 177/252

177

the steady-state response has been reached.Ex) when stop time = 25

steady-state

MATLAB : Chapter 9. Simulink

Piecewise-Linear Models

Page 178: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 178/252

178

Closed-form solutions are not available for most nonlinear differentialequations, We must solve such equations numerically.

Ex)

Piecewise-l inear models are actually nonlinear, although they mayappear to be linear.

Ex) a mass attached to a spring and sliding on a horizontal surface withCoulomb friction.

0.

5..

y y y y 0)sin(.

y y 0.

y y

0 )(

0 )(

...

...

x x x

x x x

if mg t f k m

if mg t f k m

MATLAB : Chapter 9. Simulink

Piecewise-Linear Models

Page 179: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 179/252

179

These two equations can be expressed as the single, nonlinear equation.

Solutions of models that contain piecewise-linear functions are very tediousto program. However, Simulink has built-in blocks that represent many of thecommonly-found functions such as Coulomb friction. Therefore Simulink isespecially useful for such applications. One such block is the Saturationblock in the Discontinuities library.

0 1

0 1)sing( )sing()(

......

x

x x x x x

if

if wheremg t f k m

MATLAB : Chapter 9. Simulink

Simulink Model of a Rocket-Propelledsled

Page 180: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 180/252

180

sled

A rocket propelled sled

Compute the sled‟s velocity v for 0 ≤t≤6 if v(0) = 0 The rocket thrust is 4000N and the sled mass is 450kg.The sled‟s equation of motion is

.

450 4000cos( )v

θ f

b

v

)/( 50..

srad

Page 181: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 181/252

Page 182: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 182/252

MATLAB : Chapter 9. Simulink

Simulink Model of a Rocket-Propelledsled

Page 183: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 183/252

183

s ed

④ Set the Stop time 10, run thesimulation, and examine the resultin Scope.

MATLAB : Chapter 9. Simulink

Simulink Model of a Rocket-Propelledsled

Page 184: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 184/252

184

(b)①modify the model as follows.② the Saturation block from theDiscontinuities library .Upper limit= 60*pi/180,

Lower limit=0.③mux

Generate thesolution when theengine angle θ=0.

mux

MATLAB : Chapter 9. Simulink

Simulink Model of a Rocket-Propelledsled

Page 185: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 185/252

185

Scope window

Θ=0

Θ≠ 0

MATLAB : Chapter 9. Simulink

The Relay Block

Page 186: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 186/252

186

The Simulink Relay block is an example of something that is tedious toprogram 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 Onand Off in the figure.

On

Off

SwOnSwOff

Off

OnSwOff SwOn

The relay function. (a) The case whereOn>Off. (b) The case where On<Off

(a) (b)

Page 187: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 187/252

MATLAB : Chapter 9. Simulink

Model of a Relay-Controlled Motor

Page 188: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 188/252

188

x1=i, x2= ω

R=0.6 Ω, L=0.002H, K T=0.04N·m/A, K e=0.04V·s/rad, c=0.01N·m·s/rad, andI=6·10^(-5)kg·m^2Suppose we have a sensor that measure the motor speed, and we use thesensor‟s signal to activate a relay to switch the applied voltage v(t) between0 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 -K e /L

KT/I -c/I+

1/L 0

0 -1/I

V(t)

Td(t)

On

Off

SwOnSwOff

Page 189: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 189/252

MATLAB : Chapter 9. Simulink

Model of a Relay-Controlled Motor

Page 190: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 190/252

190

①Create a new Simulink model.

②Select and place a Step block from the Sources library . Label itDisturbance Step .

Step time=0.05, Initial and Finaltime=0 and 3, Sample time=0

③Select and place a Relay blockfrom the Discontinuities library.Switch-on and Switch-off points=350 and 250,Output when on and Output whenoff=0 and 100.

MATLAB : Chapter 9. Simulink

Model of a Relay-Controlled Motor

Page 191: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 191/252

191

④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 theContinuous library .enter the A,B,C,D.enter [0;0] for the initial conditoin.B tells 2 input, C and D tells 1output.

MATLAB : Chapter 9. Simulink

Model of a Relay-Controlled Motor

Page 192: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 192/252

192

⑥Select and place the Scopeblock from the Sinks library.

⑦connect each port.

⑧Stop time=0.1 and run thesimulation. (the plot of ω (t) in thescope.)

Note :

Connect signal1(first input) to the outputof the Relay block

Connect signa2(second input) to theoutput of the Disturbance Step

Page 193: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 193/252

MATLAB : Chapter 9. Simulink

Model of a Relay-Controlled Motor

Page 194: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 194/252

194

Speed becomes constantV=100, the system achieves a steady-state condition in which the motor torque equals the sum of thedisturbance torque and the viscousdamping torque. Thus the accelerationis zero.

MATLAB : Chapter 9. Simulink

Model of a Relay-Controlled Motor

Page 195: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 195/252

195

⑨If you want examine the current i(t), change thematrix C to [1,0], and run the simulation again.

Page 196: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 196/252

MATLAB : Chapter 9. Simulink

Transfer-Function Models

Page 197: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 197/252

197

mass-spring-damper system

As with the control System toolbox, Simulink can accepts a system description in transfer-function form and in state-variable formif 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 ahydraulic piston that has a dead-zone nonlinearity. This means that the piston does notgenerate a force until the input voltage exceeds a certain magnitude.

A graph of a particular dead-zone nonlinearity is shown below.

)( t f yk yc ym

-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

00.1

0.20.30.40.5

Input

O u t p u t

MATLAB : Chapter 9. Simulink

Transfer-Function Models

Page 198: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 198/252

198

[EXAMPLE 9.5-1] Response with a Dead ZoneCreate and run a Simulink simulation of a mass-spring-damper model

m=1, c=2 and k=4f(t) = sin(1.4t)The system has the dead-zone nonlinearity shown in Figure 9.5-1

SolutionStart Simulink and construct

fallowing Simulink model

)( t f yk yc ym

MATLAB : Chapter 9. Simulink

Transfer-Function Models

Page 199: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 199/252

199

Solution (cont’d)

Details of Blocks

drag

double-click

& changeparameters

Simulink librarybrowser

MATLAB : Chapter 9. Simulink

Transfer-Function Models

Page 200: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 200/252

200

solution (cont’d)

Modification of the dead-zone model to include aMux blockTo plot both the input and the output of theTransfer Fcn block versus time on the same graph.

(More informative)

dragdouble-click& changeparameters

Page 201: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 201/252

MATLAB : Chapter 9. Simulink

Nonlinear State-Variable Models

Page 202: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 202/252

202

Solution

let

)(sin108.025.0)(sin1 t M t M mgLc I

Integrate both sides of each equation over time to obtain

dt t M

dt

)(sin108.025.0

MATLAB : Chapter 9. Simulink

Nonlinear State-Variable Models

Page 203: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 203/252

203

Solution (cont‟d) Construct following Simulink model

Select blocks and place them.Double-click blocks and change parameters.

θ θ

initial = 0

initial = pi/4

MATLAB : Chapter 9. Simulink

Nonlinear State-Variable Models

Page 204: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 204/252

204

Solution (cont‟d) Details of new blocks

drag

double-click& change

parameters

MATLAB : Chapter 9. Simulink

Nonlinear State-Variable Models

Page 205: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 205/252

205

Solution (cont‟d) Simulation result

NoteTo flip the box left to right, right-click on it, select Filp“Fnc” block : General expression block. Use “u” as input variable name.

MATLAB : Chapter 9. Simulink

Subsystems

Page 206: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 206/252

206

To simulate a complex system, the diagram can become rather largeand therefore some what cumbersome.Simulink, however, provides for the creation of s u b s y s t e m b l o c k s

S u b s y s t em b l o c k play a role analogous to that of subprograms in a programming languagea Simulink program represented by a single block.can be used in other Simulink programs.

Example – A Hydraul ic System

MATLAB : Chapter 9. Simulink

Subsystems

Page 207: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 207/252

207

Example – A Hydraul ic System liquid mass density ρ cylindrical tank with a bottom area Amass 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 resistanceto 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

momi qqdt

dh A

dt

dm

h R g

qdt dh

A mo

R gh

p p gh R

q aamo

])[(1

R g As sQ s H

mi /1

)()(

MATLAB : Chapter 9. Simulink

SubsystemsExample – A Hydraulic System (cont’d)

Page 208: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 208/252

208

Example A Hydraulic System (cont d)

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 signed-square-root relation

where q mo is the outlet mass flow rate, R is the resistance, Δ p is the pressure differenceacross 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 signed-square-root relationthen the model of the system is

)(1

pSSR R

qmo

00)(

pif p pif p pSSR

)(1

)(1

r r

l l

p pSSR R

p pSSR R

qdt dh

A

MATLAB : Chapter 9. Simulink

Subsystems

Page 209: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 209/252

209

Create a subsystem blockdrag the Subsystem block from the libraryor first creation a Simulink model and then “encapsulating”

Create s subsystem block for the liquid-level system shown in Figure 9.7-2.First construct the Simulink model as fallow

input port(Ports and

Subsystemslibrary)

output port(Ports and

Subsystemslibrary)

MATLAB : Chapter 9. Simulink

SubsystemsCreate s subsystem block (Cont‟d)

Page 210: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 210/252

210

Create s subsystem block (Cont d) create a “bounding box” surrounding the diagram. (holding the mouse button down, anddragging)choose Create Subsystem from the Edit menu. (or in the Right-click menu)

The result

MATLAB : Chapter 9. Simulink

Subsystems

Page 211: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 211/252

211

Connecting Subsystem Blockscreate a simulation of the system shown below

where the mass inflow rate q is a step function

Simulink model of the systemDouble-click subsystem block Tank 1 and changeparameters.

1/R_l=0; 1/R_r=1/R_1; 1/rho*A=1/rho*A_1initial condition of the integrator to h10

in Tank 21/R_l = 1/R_1; 1/R_r = 1/R_2; 1/rho*A=1/rho*A_2initial condition of the integrator to h20

Page 212: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 212/252

MATLAB : Chapter 9. Simulink

Dead Time in Models

Page 213: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 213/252

213

Dead Time (transport delay)a time delay between an action and its effect.The transfer function for a dead-time 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 typicallyoccurs as a delay between a change in the actuator signal and its effect on thesystem 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 dead-time processes is difficult, and often simulation is the only practicalway to study such processes.Easily simulated in Simulink. Using “Transport Delay” Block.

Tse

2/111

22 sT Tsee Ts

Ts

MATLAB : Chapter 9. Simulink

Dead Time in Models

Page 214: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 214/252

214

Consider the model of the height h of liquid in a tank.input is a mass flow rate qiit takes a time T for the change in input flow to reach thetank following a change in the valve opening.the transfer function

Simulink model for this system

15 2)( )( se sQ s H Ts

i

MATLAB : Chapter 9. Simulink

Dead Time in ModelsTransport Delay block

Page 215: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 215/252

215

Transport Delay block

in Continuous libraryDouble-click the block and set the delay to 1.25

Transfer Fcn (with initial outputs) block

Double-click the block and set the initial output to 0.2The Saturation and Rate Limiter Blocks

suppose that the minimum and maximum flow rates available from the input flow valve are0 and 2In additional, some actuators have limits on how fast they can react. (to avoid damage tothe unit)Saturation block

in Discontinuity libraryDouble-click the block and set the Upper limit to 2, the Lower limit to 0

Rate Limiter blockin Discontinuity library Double-click the block and set the Rising slew rate to 2, the Falling slew rate to 0

MATLAB : Chapter 9. Simulink

Dead Time in Models

A C t l S t

Page 216: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 216/252

216

A Control SystemThe Simulink model shown in Figure 9.8-1 is for a specific type of control system called a PIcontroller.whose response f(t) to the error signal e(t) is the sum of a term proportional to the error signaland 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 unit-step command representing the desiredheight and the actual height.In transform notation

In Figure 9.8-1, we used the values K P=4 and K I=5/4.

Simulation ResultStop 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

Simulation of a Vehicle Suspension

Page 217: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 217/252

217

Often in the design of an engineering system, we must eventually dealwith nonlinearities in the system and with more complicated inputs suchas trapezoidal functions, and this must often be dome with simulation.In this section we introduce four additional Simulink elements that enableus to model a wide range of nonlinearities and input functions,

the Derivative block,the Signal Builder block,the Look-Up Table block, andthe MATLAB Fcn block

As our example, we will use the

single-mass suspension modelshown in Figure 9.9-1

MATLAB : Chapter 9. Simulink

Simulation of a Vehicle SuspensionSingle-mass model of a vehicle suspension

Page 218: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 218/252

218

g p

the spring and damper forces fs and fd have the nonlinear models shown inFigures 9.9-1 and 9.9-3

The bump is represented by the trapezoidal function y(t) shown in Figure 9.9-4

MATLAB : Chapter 9. Simulink

Simulation of a Vehicle Suspension

Page 219: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 219/252

219

The system model from Newton‟s law is

where m = 400 kg, is the nonlinear spring fuction shown in Figure 9.9-2and is the nonlinear damper function shown n Figure 9.9-3

The corresponding simulation diagram

)..

()(..

x y f x y f xm d s

)( x y f s

)..

( x y f d

MATLAB : Chapter 9. Simulink

Simulation of a Vehicle SuspensionSimulink model of a vehicle suspension system.

Page 220: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 220/252

220

The Derivative BlockSimulink uses numerical methods,it computes derivatives only approximately

in Continuous libraryThe Signal Builder Blocks

in Source librarydouble-click and create the functionshown in Figure 9.9-4

MATLAB : Chapter 9. Simulink

Simulation of a Vehicle Suspension

Page 221: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 221/252

221

The look-Up Table BlockThe spring function fs is created with the Look-Up Table block.In Lookup Tables librarydouble-click on it and enter [-0.5, -0.1, 0, 0.1, 0.5] for the Vector of input valuesand [-4500, -500, 0, 500, 4500] for the Vector of output values.

To Workspace block and the Clockenable us to plot x(t) and y(t)-x(t) versus t in the MATLAB Command window.

The MATLAB Fcn Blockwe must write a user-definedfunction to describe the damper function.

double-click on the block andchange function name.

MATLAB : Chapter 9. Simulink

Simulation of a Vehicle Suspension

Page 222: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 222/252

222

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 )

Page 223: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 223/252

MATLAB

CHAPTER 10Symbolic processing with MATLAB

MATLAB : Chapter 10. Symbolic processing with MATLAB

OUTLINE

Page 224: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 224/252

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 s y m function Symbolic expressions

Page 225: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 225/252

The s y m 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)')

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)Manipulating expressions

Page 226: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 226/252

ex >>syms x y>>expand((x+y)^2)

% applies algebra rulesans =

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

collect (E)

ex >>syms x y>>E=(x-5)^2+(y-3)^2;>>collect (E)

ans =

x^2-10*x+25+(y-3)^2

>>collect(E,y)ans =

y^2-6*y+(x-5)^2+9

MATLAB : Chapter 10. Symbolic processing with MATLAB

Symbolic expressions and algebra(3/10)

factor (E) Ex> >>syms x y

Page 227: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 227/252

factor (E)ex >>syms x y

>>factor(x^2-1)ans =

(x-1)*(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)

y y

>>E1=x^2+5; % define two expressions>>E2=y^3-2;>>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 expressionsS2 =(x^2+5)*(y^3-2)

>>expand(S2) % expand the productans =

x^2*y^3-2*x^2+5*y^3-10>>S3=E3/E1 % divide two expressions

S3 =(x^3+2*x^2+5*x+10)/(x^2+5)

>>simplify(S3) % see if some terms cancelans =

x+2

MATLAB : Chapter 10. Symbolic processing with MATLAB

Symbolic expressions and algebra(4/10)

Page 228: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 228/252

[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*sqroot2y =

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)

Page 229: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 229/252

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^2-3*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 (n-1)!

Page 230: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 230/252

ex (n-1)!>> kfac=sym('k!');>> syms k n>> E=subs(kfac,k,n-1)

E =(n-1)!

>> 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)

Page 231: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 231/252

Evaluating expressionsex >> 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 thecurrent 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)

Page 232: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 232/252

Plotting expressionsezplot (E)explot ( E, [xmin xmax] )

ex >> syms x

>> E=x^2-6*x+7;>> ezplot(E,[-2 6])

MATLAB : Chapter 10. Symbolic processing with MATLAB

Symbolic expressions and algebra(9/10)Order of precedenceex syms x

E=x^2-6*x+7;F=-E/3

F = -1/3*x^2+2*x-7/3normally F= - (x2-6x+7)/3

Page 233: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 233/252

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 theindependent variable is the interval [-2 π , 2 π ] unless this interval contains a singularity. The optional formezplot (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 symbolicexpression, and returns a string containing all the symbolic variables appearing in E. the variables arereturned 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 objectsin 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

MATLAB : Chapter 10. Symbolic processing with MATLAB

Symbolic expressions and algebra(10/10)

Functions for creating and evaluating symbolic expressions

Page 234: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 234/252

g g y p

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 formpoly2sym(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. Whencalled, the function displays the results of each step of its search. When called without theargument, simple acts on the previous expression. The form [ r, how] = simple (E) does notdisplay intermediate steps, but saves those steps in the string how. The shortest form foundis stored in r .

simplify (E) Simplify the expression E using Maple‟s 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.

Page 235: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 235/252

MATLAB : Chapter 10. Symbolic processing with MATLAB

Algebraic and transcendental equations(2/3)

Page 236: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 236/252

solve ( E, 'v')

ex >> solve('b^2+8*c+2*b=0') % solves for c becauseit is closer to xans =

-1/8*b^2-1/4*b

ex >> solve('b^2+8*c+2*b=0','b') % solves for bans =

[ -1+(1-8*c)^(1/2)][ -1-(1-8*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.xx =

1>> y=ans.yy =

4ex >> [x ,y] = solve(eq4,eq5)

>> S=solve(eq4,eq5)S=

x : [1x1 sym]y : [1x1 sym]

>> S.xans=

1>> S.yans =

4

MATLAB : Chapter 10. Symbolic processing with MATLAB

Algebraic and transcendental equations(3/3)

Page 237: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 237/252

Command Description

solve (E) Solves a symbolic expression or equation represented by the

expression E. if E represents an equation, the equation‟s 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)

Page 238: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 238/252

diff (E)1n

n

nxdx

dxex

>> syms n x y>> diff(x^n)ans =

x^n*n/x>> simplify(ans)ans =

x^(n-1)*n

xdx xd 1lnex

>> diff(log(x))

ans =1/x

x xdx

xd cossin2sin2ex

>> diff((sin(x) 2)

ans =2*sin(x)*cos(x)

ydy

yd cos

sinex

>> diff((sin(y))

ans =cos(y)

MATLAB : Chapter 10. Symbolic processing with MATLAB

Calculus (differentiation) (2/9))sin(),( xy y x f ex

Page 239: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 239/252

)cos( xy ydxdf

2 x

>> 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 xex

>> 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)

xdx

xd 6

)(2

32

ex

>> syms x>> diff(x^3,2)ans =

6*x

)sin()]sin([ 32

2

xy x y

xy xex

>> 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)

Page 240: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 240/252

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 xn

n

xdx x

ln1

x xdx sincos

y ydy cossin

MATLAB : Chapter 10. Symbolic processing with MATLAB

Calculus (integration) (4/9)

xn

Page 241: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 241/252

xdn xnlnex

>> syms n x>> int(x^n,n)

ans =1/log(x)*x^n

int (E, v)

int (E, a, b) 393

52

5

2

32 xdx xex

>> syms x

>> int(x^2,2,5)

ans =39

MATLAB : Chapter 10. Symbolic processing with MATLAB

Calculus (integration) (5/9)

Page 242: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 242/252

33

332 abdx x

b

a

int (E, v, a, b)

x y

xdy xy3

1253

50

35

0

2ex

>> 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^3-1/3*a^3

t e x xdx

t x

dx x

t e

t

et

t t

t t

cos)cos(cossin

21

21

22

1

2

1ex

>> syms t x>> int(x,1, t)

ans = 1/2*t^2-1/2>> int(sin(x),t,exp(t))ans =

-cos(exp(t))+cos(t)

1ln1

1xdx

xex

>> syms x>> int(1/(x-1))ans =

log(x-1)>> int(1/(x-1),0,2)ans =

NaN :singularity at x=1

MATLAB : Chapter 10. Symbolic processing with MATLAB

Calculus (Taylor series) (6/9)

Taylor‟s theorem

Page 243: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 243/252

taylor (f, n, a)

ex x x x x

x x ,!7!5!3

sin753

x x x x

x ,!6!4!2

1cos642

x x x x

xe x ,!4!3!2

1432

nb xn

n

n a xdx

f d n

R )(!

1

nk

a xk

k

a xa x Ra xdx

f d k

a xdx

f d a x

dxdf

a f x f

)(!

1)(

21

)()()( 22

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)*(x-2)+1/2*exp(2)*(x-2)^2

ex

])2(21

)2(1[ 22 x xe=( )

MATLAB : Chapter 10. Symbolic processing with MATLAB

Calculus (sums) (7/9)symsum (E)

Page 244: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 244/252

S = symsum (E, a, b) >> syms k n>> symsum(k,0,10)ans =

55

>> symsum(k,0,n-1)ans =

1/2*n^2-1/2*n

>> factor(ans)ans =

1/2*n*(n-1)

>> 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 55109321010

0k

k

nnnk n

k 21

21

13210 21

0

30169414

1

2

k

k

ex

MATLAB : Chapter 10. Symbolic processing with MATLAB

Calculus (limits) (8/9)

Page 245: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 245/252

limit (E, a) ( )

limit (E) : limit as

limit (E, v, a) : limit as

>> syms h x>> limit((x-3)/(x 2-9),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

x1

lim

x1

lim

0 x

0 x

ex

>> syms a x>> limit(sin(a*x)/x)ans =

a

a x

ax)sin(lim

0 x

av

ex 6

1

9

3

lim 2 x

x

h xh x )sin()sin(

lim

3 x

0h

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.

Symbolic calculus functions

Page 246: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 246/252

diff (E,v) Returns the derivative of the expression E with respect to the variable v.diff (E,n) Returns the n th 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 beright or left.

symsum (E) Returns the symbolic summation of the expression E.

taylor (f,n,a) Gives the first n-1 terms in the Taylor series for the function defined in the expression f , evaluated at the pointx=a . If the parameter a is omitted, the function returns the series evaluated at x=0 .

MATLAB : Chapter 10. Symbolic processing with MATLAB

Differential Equations (1/6)

Page 247: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 247/252

Solving a Single Differential EquationThe dsolve function‟s syntax: dsolve („eqn‟) → returns a symbolic solution of theODE 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)

122 ydt dy t eC t y 2

16)(Ana ly t ic so lu t ion :

A symbolic solution using the dsolve function .

MATLAB : Chapter 10. Symbolic processing with MATLAB

Differential Equations (2/6)

Page 248: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 248/252

Solving Sets of EquationsThe appropriate syntax: dsolve („eqn1‟, „eqn2‟,…) → returns a symbolic solutionof the set of equations specified by the symbolic expressions eqn1 and eqn2 .

(example)

y xdt dy

y xdt dx

34

43Ana ly t ic so lu t ion :

t eC t eC t y

t eC t eC t xt t

t t

4cos4sin)(

4sin4cos)(3

23

1

32

31

MATLAB : Chapter 10. Symbolic processing with MATLAB

Differential Equations (3/6)

f l d d d

Page 249: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 249/252

Specifying Initial and Boundary ConditionsThe appropriate syntax: dsolve(„eqn‟,‟cond1‟,‟cond2‟) → returns a symbolicsolution of the ODE specified by the symbolic expression eqn , subject to theconditions specified in the expressions cond1 , cond2 , and so on.

(example)

22

2 , (0) 1, (0) 0d y

c y y ydt

2/)()( ct ct eet yAna ly t ic so lu t ion :

MATLAB : Chapter 10. Symbolic processing with MATLAB

Differential Equations (4/6)

Pl i h S l i (1)

Page 250: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 250/252

Plotting the Solution (1)The ezplot function can be used to plot the solution

(example)

0)0(),4sin(41010 yt ydt

dy

Ana ly t ic so lu t ion :

t et t t y 10

2925

)4sin(2910

)4cos(294

1)(

0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 50

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8

2

t

1-4/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)

Pl i h S l i (2)

Page 251: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 251/252

Plotting the Solution (2)Sometimes the ezplot function uses too few values of the independent variableand 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 sy mbo l ic var iable.

MATLAB : Chapter 10. Symbolic processing with MATLAB

Differential Equations (6/6)

(T bl 10 4 1) Th d l f ti

Page 252: Bai Giang Matlab_55m

7/30/2019 Bai Giang Matlab_55m

http://slidepdf.com/reader/full/bai-giang-matlab55m 252/252

(Table 10.4-1) The dsolve function

Command Description

dsolve(„eqn‟) Returns a symbolic solution of the ODE specified by the symbolicexpression eqn . Use the uppercase letter D to represent the firstderivative; use D2 to represent the second derivative, and so on.

Any character immediately following the differentiation operator istaken to be the dependent variable.

dsolve(„eqn1‟,‟eqn2‟,…) Returns a symbolic solution of the set of equations specified bythe symbolic expressions eqn1 , eqn2 , and so on.

dsolve(„eqn‟,‟cond1‟,‟cond2‟,…) Returns a symbolic solution of the ODE specified by the symbolic