Matlab Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 207

Chapter 1 MATLAB

Intro to MATLAB  MATLAB stands for


Matrix Laboratory
 MATLAB programming for Engineering
introduces the MATLAB R2015b
 http://ist.njit.edu/software/download
 O n the entry “MATLAB”
 Click “Download from Product Site”
 You need to re gister an account at
www.m athwork s.com

dr.dcd.h CS 101 /SJC 5th Edition 1 dr.dcd.h CS 101 /SJC 5th Edition 2

Advantages of MATLAB Disadvantages of MATLAB


 Easy to use  MATLAB is based on an interpreted language and it
m ay execute slower than compiled programs.
 Platform Independence
 A full copy of MATLAB is 5 to 10 times more
 Predefined Functions e x pensive than a C/C++/Fortran compiler.
 Device- Independent Plotting
 Graphical User Interface
 MATLAB Compiler

dr.dcd.h CS 101 /SJC 5th Edition 3 dr.dcd.h CS 101 /SJC 5th Edition 4

1
MATLAB Environment The MATLAB Desktop
 In Windows or Apple operating systems  MATLAB uses several different windows to
click on the desktop icon or menu item display data, commands and results.
- comand window
- toolstrip
- command history window
- document window
- figure window
 In Unix/MSDOS type MATLAB at the
- workspace browser
shell prompt - current folder browser
- help browser
- path browser

 They are not necessarily all open at once.

dr.dcd.h CS 101 /SJC 5th Edition 5 dr.dcd.h CS 101 /SJC 5th Edition 6

The MATLAB Desktop2 The Command Window

Command Window

dr.dcd.h CS 101 /SJC 5th Edition 7 dr.dcd.h CS 101 /SJC 5th Edition 8

2
The Command Window2 The Toolstrip
 A user can enter interactive commands at  The controls on the Toolstrip are organized
the command prompt (>>) in the into related categories of functions, first by
command window. tabs and then by goups.
 A user can place a series of commands into  The Quick Access Toolbar is a place where
a script file, and the entire file can be the user can customize the interface.
executed by typing its name in the
command window.
 MATLAB script files are also known as M-
files, because they have a file extension of
“.m”.

dr.dcd.h CS 101 /SJC 5th Edition 9 dr.dcd.h CS 101 /SJC 5th Edition 10

The Command History The Command History2


 You can transfer commands from the
command history to the command window
 Double click on a command
 C lick and drag a command
 Use arraw k eys to select a command
 To delete commands from The History
Command History
 Se le ct a command or commands
 R ight-click with the mouse and select delete
 O r se lect clear to clear the entail history

dr.dcd.h CS 101 /SJC 5th Edition 11 dr.dcd.h CS 101 /SJC 5th Edition 12

3
The Document Window The Document Window2
 It is also called Edit/Debug Window.
 An Edit Window is created when you create
a new M-file or open an existing one.
 There are several ways to open an editing
window:
 Click the New Script icon
 Click the Ne w icon and then select Script
 Type edit w/ or w/o a name from the command
window the n hit return

dr.dcd.h CS 101 /SJC 5th Edition 13 dr.dcd.h CS 101 /SJC 5th Edition 14

The Document Window3 Figure Window


 The figure window is used to display
graphics.
 A figure can be a two- or three-dimensional
plot of data.
 When figures are created a new window
automatically opens.
 Figure window can be cleared by clf.

dr.dcd.h CS 101 /SJC 5th Edition 15 dr.dcd.h CS 101 /SJC 5th Edition 16

4
Figure Window2 Docking & Undocking Windows
 When a window is docked, it appears as a
pane within the MATLAB desktop.

dr.dcd.h CS 101 /SJC 5th Edition 17 dr.dcd.h CS 101 /SJC 5th Edition 18

Docking & Undocking Windows2 The MATLAB Workspace


 To undocking clicks the down-arrow icon to  A workspace is the collection of all the
the upper-right corner of a pane. variables and arrays that are defined within
the command window.
 This window is also called the Workspace
Browser.
 A list of variables and arrays in the currect
workspace can be generated with the who
or whos command.

dr.dcd.h CS 101 /SJC 5th Edition 19 dr.dcd.h CS 101 /SJC 5th Edition 20

5
The MATLAB Workspace2 The MATLAB Workspace3
 The who and whos commands.  Use clear to delete a variable.
 Syntax: clear [variable-list]

dr.dcd.h CS 101 /SJC 5th Edition 21 dr.dcd.h CS 101 /SJC 5th Edition 22

Array Editor Array Editor2


 Double clicking on any variable in the
workspace will bring up the Array Editor.

dr.dcd.h CS 101 /SJC 5th Edition 23 dr.dcd.h CS 101 /SJC 5th Edition 24

6
Array Editor3 Current Folder
 Also called the current directory.
 It shows all the files in the selected folder.

dr.dcd.h CS 101 /SJC 5th Edition 25 dr.dcd.h CS 101 /SJC 5th Edition 26

Current Folder2 Getting Help


 It allows the user to manipulate files  Use the Help Browser.
interactively.

dr.dcd.h CS 101 /SJC 5th Edition 27 dr.dcd.h CS 101 /SJC 5th Edition 28

7
Getting Help2 Getting Help3
 To show the usage of a known command,  To search a command by keyword, using
using the help command. the lookfor command.

dr.dcd.h CS 101 /SJC 5th Edition 29 dr.dcd.h CS 101 /SJC 5th Edition 30

Useful Commands Useful Commands2


 who  Type demo in the command window.
 whos
 clear [var_list]
 more on/off
 Ctrl-C (or ^C )
 clc (not cls)
 clf
 help com mand
 lookfor k eyword
 demo
 which com mand

dr.dcd.h CS 101 /SJC 5th Edition 31 dr.dcd.h CS 101 /SJC 5th Edition 32

8
Useful Commands3 MATLAB Search Path
 To find out where a command is located,  If a name is typed at the system prompt,
using the which command. the MATLAB interpreter attempts to find the
command as follows:
 C he cks as a variable in the workspace.
 Che cks as an M-file in the current folder.
 Che cks to see if it is an M-file in any directory
along the MATLAB search path.

dr.dcd.h CS 101 /SJC 5th Edition 33 dr.dcd.h CS 101 /SJC 5th Edition 34

MATLAB Search Path2 Red Flags


 Type path at the system prompt, the  Don’t do the followings intentionally:
MATLAB search path will be listed.  Do not use a variable with the same name as a
system function or command.
 Do not create an M-file with the same name as a
system function or command.

dr.dcd.h CS 101 /SJC 5th Edition 35 dr.dcd.h CS 101 /SJC 5th Edition 36

9
Homework Assignment #1 How to Make Homework
 1.6 Exercises  Make sure your command window is under
 Page 24: 1.1, 1.3, 1.4, 1.8, 1.9, 10 format compact;
 This assignment is due by next week.  Enter the homework questions line-by-line;
 Late submission will be penalized.  Copy and paste the outputs including the
 Hand-written homework will not be commands into a word document and
accepted or graded. select the minimum spacing;
 Hand in a hardcopy of your homework, no  Save figures into image files and then
electronic submission will be accepted. insert them into your document. You may
need to change their sizes;
 Print your homework to a nearby printer.

dr.dcd.h CS 101 /SJC 5th Edition 37 dr.dcd.h CS 101 /SJC 5th Edition 38

How to Make Homework2 How to Make Homework3

dr.dcd.h CS 101 /SJC 5th Edition 39 dr.dcd.h CS 101 /SJC 5th Edition 40

10
How to Make Homework4

dr.dcd.h CS 101 /SJC 5th Edition 41

11
9/4/2018

Chapter 2 (Part 1) Arrays


MATLAB Basics  The fundamental unit of data in MATLAB is
the array.
 An array is a collection of data values
organized into rows and columns and is
known by a specified name.
 Individual data values within an array are
accessed by a name and subscripts of
indexes.
 For example: abc(1,2)

dr.dcd.h CS 101 /SJC 5th Edition 1 dr.dcd.h CS 101 /SJC 5th Edition 2

Arrays2 Arrays3
 A single value is called a scalar  The size of an array is specified by the
 Matrix with only one row and one column number of rows and the number of
 This is a 4x6 matrix, containing 24 columns.
elements.  [ ] creates an empty array.
3 0 0 4 4 0
0 3 0 4 4 0
 Data in an array are listed in row order,
1 1 3 4 4 1 i.e. the items in each row are listed from
0 0 1 1 1 0 left to right, with the topmost row first.
 Syntax: var(row, col)
 [1, 2, 3, 4] is a 1x4 array, known as a row
vector.
 A 4x1 array is called a column vector.

dr.dcd.h CS 101 /SJC 5th Edition 3 dr.dcd.h CS 101 /SJC 5th Edition 4

Variables Variables2
 A MATLAB variable is a region of memory  There are certain keywords you can’t use
containing an array, which is known by a  Use iskeyword function to check
user-specified name. whether a name is a system reserved
 Variable names must start with a letter. name.
 They may contain letters, numbers and the
underscore ( _ ).
 Names are case sensitive.
 The effective length of a name is 63
characters.

dr.dcd.h CS 101 /SJC 5th Edition 5 dr.dcd.h CS 101 /SJC 5th Edition 6

1
9/4/2018

Variables3 Variables4
 MATLAB will let you use built-in function  Use command clear (check Chap 1)
names as variables – but it’s a really bad  Then how to clear an accidently created
idea. variable named as clear?
 What if you accidently overwritten a
function to a variable name?

dr.dcd.h CS 101 /SJC 5th Edition 7 dr.dcd.h CS 101 /SJC 5th Edition 8

Naming Variables Basic Data Types


 test  The most common types of MATLAB
 Test
 if
variables are double and char.
x
 my-book
x  A variable of type double consists of 64-bit
 my_book double-precision floating-point values.
 Thisisoneverylongnamebutisitstillallowed?
x
 1stgroup
x
 Variable of type char consist of scalars or
 group_one arrays of 16-bit values.
 zzaAbc
 z34wAwy?12#
x x
 sin bad
 log idea

dr.dcd.h CS 101 /SJC 5th Edition 9 dr.dcd.h CS 101 /SJC 5th Edition 10

Default Data Type Assignment Operator


 By default, a variable of type double is  = is the assignment operator
automatically created whenever a syntax: var_name = expression;
numerical value is assigned to a name
 An expression is a value, an array, or a
 It can be positive or negative number in the
range of 10-386 to 10386, with 15 t o16 significant combination of values, other variables, and
decimal digits. mathematical operations.
 To define a variable a we might type
a=10.5
which should be read as:
a is assigned a value of 10.5

dr.dcd.h CS 101 /SJC 5th Edition 11 dr.dcd.h CS 101 /SJC 5th Edition 12

2
9/4/2018

Data Initialization Data Initialization2


 MATLAB variables are automatically created
when they are initialized.
 a=10.5
 b=’abc’, c=4+3i
 d=[1 2 3 4];

dr.dcd.h CS 101 /SJC 5th Edition 13 dr.dcd.h CS 101 /SJC 5th Edition 14

Data Initialization3 Creating Variables


 The size of an array is specified by the
number of rows and the number of
columns.
 [ ] creates an empty array.
 In MATLAB, transpose matrix MT is denoted
as M’, ’ is a transpose operator
 The transpose operator changes rows to columns
or vice versa.
 The transpose operator makes it easy to create
tables

dr.dcd.h CS 101 /SJC 5th Edition 15 dr.dcd.h CS 101 /SJC 5th Edition 16

Creating Variables2 Creating Variables3

[degrees;radians]’ would
have given the same result

The transpose operator


makes it easy to create tables

dr.dcd.h CS 101 /SJC 5th Edition 17 dr.dcd.h CS 101 /SJC 5th Edition 18

3
9/4/2018

Creating Tables Creating Arrays


 The transpose operator makes it easy to
create tables

dr.dcd.h CS 101 /SJC 5th Edition 19 dr.dcd.h CS 101 /SJC 5th Edition 20

Creating Arrays2 Shortcut Expressions


 Evenly spaced numerical sequence can be
created by shortcut expressions.
 The general form of a colon operator
 first:increment:last

 This expression creates an arrary of


[first, first+incr, first+incr*2, …]
until the value is greater than the last.
 If the stepping increment is one, then the
middle argument can be ignored
 first:last

dr.dcd.h CS 101 /SJC 5th Edition 21 dr.dcd.h CS 101 /SJC 5th Edition 22

Shortcut Expressions2 Shortcut Indexing


 The general form of indexing is (row, col)
 Color operator can be used to represent a
range of indexes, i.e. a sub-region inside
an array
 n:m represents indexes from n to m.

 ’:’ can be used to represent all the indexes

 [p q …] represents positions of pth, qth, and etc.

dr.dcd.h CS 101 /SJC 5th Edition 23 dr.dcd.h CS 101 /SJC 5th Edition 24

4
9/4/2018

Shortcut Indexing2 Build-In Functions


 Build-in functions zeros, ones, and eye
can be used to create all zeros, all ones,
and identity matrices of any size.
 If the function has a single argument, it will
produce a squared array of the given value.
 For example:
eye(2) is the same as eye(2, 2)

dr.dcd.h CS 101 /SJC 5th Edition 25 dr.dcd.h CS 101 /SJC 5th Edition 26

Build-In Functions2 Build-In Functions3


 How to use only 4 statements to produce
the following matrix?

dr.dcd.h CS 101 /SJC 5th Edition 27 dr.dcd.h CS 101 /SJC 5th Edition 28

Build-In Functions4 Build-In Functions5


 length returns the length of a vector, or
the longest dimension of a matrix.
 size returns all the dimensions of a
variable.
 Nested function: the output of an inner
function is used as a corresponding
argument of an outer function.
 For example: to create a new array b by
duplicating the size of another array a
b=zeros(size(a))
ndims(z)=length(size(z))

dr.dcd.h CS 101 /SJC 5th Edition 29 dr.dcd.h CS 101 /SJC 5th Edition 30

5
9/4/2018

Keyboard Input Keyboard Input2


 To allow a M-script to prompt a user for
input interactively.
 The input function displays a prompt string
in the command window and then waits for
the user to type in a response at the
keyboard
 input(prompt_string)
 input(prompt_string, string_option)
 If no receiving variable is specified, the
default variable ans is used

dr.dcd.h CS 101 /SJC 5th Edition 31 dr.dcd.h CS 101 /SJC 5th Edition 32

Keyboard Input3 Homework Assignment #2


 If sting option is used, then whatsoever  Quiz 2.1
entered will be treated as characters.  Page 36: 2, 3, 4, 5, 6, 7
 This assignment is due by next week.
 Late submission will be penalized.
 Hand-written homework will not be
accepted or graded.
 Hand in a hardcopy of your homework, no
electronic submission will be accepted.

dr.dcd.h CS 101 /SJC 5th Edition 33 dr.dcd.h CS 101 /SJC 5th Edition 34

Multidimensional Arrays Multidimensional Arrays2


 Sometimes you may want to store data in  Multidimensional arrays are based on 2D
multidimensional arrays pages.
 Rows
 Columns
 Pages
 Additional dimensions are possible

dr.dcd.h CS 101 /SJC 5th Edition 35 dr.dcd.h CS 101 /SJC 5th Edition 36

6
9/4/2018

Multidimensional Arrays3 Multidimensional Arrays3


 A multidimensional array can also be  We say that a matrix is stored in row major
formed by adding 2D pages. order if it is stored row by row. The entire
first row is stored first. On the other hand,
it is in column major order if it is stored
column by column.
 For example: consider the matrix

 In the row-major order layout:

 In the column-major order layout:

dr.dcd.h CS 101 /SJC 5th Edition 37 dr.dcd.h CS 101 /SJC 5th Edition 38

Memory Allocations Memory Allocations2


 In MATLAB, elements of an array are  To access to the memory directly, use
allocated in column-major order. single indexing, such as A(3).

7 9 11
8 10 12
1 3 5
2 4 6

dr.dcd.h CS 101 /SJC 5th Edition 39 dr.dcd.h CS 101 /SJC 5th Edition 40

Memory Allocations3 Sub-Arrays


 We can modify data by applying the  Use shortcut indexing first:incr:last to
modifications directly to the memory. reference to a subarray.
 For example: consider the matrix

A(1:2:3, :)=[1 2 3; 7 8 9]

A(6)=8 and A(8)=6

dr.dcd.h CS 101 /SJC 5th Edition 41 dr.dcd.h CS 101 /SJC 5th Edition 42

7
9/4/2018

The end Function Reference to Sub-Arrays


 The keyword end returns the highest index
in an array subscript.
 For example: consider the following matrix A
?:n:? refers every n
element
Keyword end returns
the highest subscript
A(end, end) is referenced to A(4, 6)
Reassign sub-matrix
by specifying indexes
Both sides must have
the same shape, 2x2

dr.dcd.h CS 101 /SJC 5th Edition 43 dr.dcd.h CS 101 /SJC 5th Edition 44

Pre-defined Keywords Homework Assignment #3


Keyword Predefined value  Quiz 2.2
pi 3.141592653589793  Page 44: 1, 2, 3
____
i, j P-1  This assignment will due next week.
inf , infinite  Late submission will be penalized.
NaN Not-a-Number  Hand-written homework will not be
clock current date and time accepted or graded.
date current date in string form  Hand in a hardcopy of your homework, no
eps smallest difference between numbers electronic submission will be accepted.
ans the variable stores the unassigned result

dr.dcd.h CS 101 /SJC 5th Edition 45 dr.dcd.h CS 101 /SJC 5th Edition 46

8
9/4/2018

Chapter 2 (Part 2) Display Format


MATLAB Basics  In the command window, integers are
always displayed as integers
 Characters are always displayed as strings
 Other values are displayed using a specified
display format
 No matter what display format you choose,
MATLAB uses double precision floating
point values in its calculations

dr.dcd.h CS 101 /SJC 5th Edition 1 dr.dcd.h CS 101 /SJC 5th Edition 2

Display Format2 Display Format2


 The display format can be changed by  The default format shows four digits after
using format command the decimal point, it is also known as short
 For example: format short format Descriptions Example
short 4 digits after decimal 3.1416
 Default display format can be changed via long 14 digits after decimal 3.141592653589793
the Preferences manually short e 5 digits plus exponent 3.1416e+000
short g 5 digits plus w/ or w/o exponent 3.1416
long e 15 digits plus exponent 3.141592653589793e+000
long g 15 digits plus w/ or w/o exponent 3.14159265358979
bank dollars and cents format 3.14
hex 4-bit hexadecimal 400921fb54442d18
rat approximate ratio of small integers 355/113
compact approximate ratio of small integers
loose restore extra line feeds
+ only displays signs +

dr.dcd.h CS 101 /SJC 5th Edition 3 dr.dcd.h CS 101 /SJC 5th Edition 4

The disp Function The disp Function2


 The disp function displays the contents of a  To represent report that contains numbers
numerical matrix or a string and string, the following converting
 The general form of disp function functions can be used:
 disp(variable)  num2str: convert a number to a string
 int2str: convert an integer to a string

dr.dcd.h CS 101 /SJC 5th Edition 5 dr.dcd.h CS 101 /SJC 5th Edition 6

1
9/4/2018

The disp Function3 Formatted Output: fprintf


 To include an apostrophe (’) in a string,  fprintf function displays one or more
you need to enter the apostrophe twice. It values together with related text and
is easier to think the syntax contains two provides control over the way values are
strings. displayed.
 disp( ’I’’m what I am’ )  The general form of fprintf function
 fprintf(format, data)
 format is a string describing the way the data is
to be printed
 data is one or more scalars or arrays

dr.dcd.h CS 101 /SJC 5th Edition 7 dr.dcd.h CS 101 /SJC 5th Edition 8

Formatted Output: fprintf2 Formatted Output: fprintf3


 The general form of disp function  Common conversion characters:
 fprintf(format, data)
%? Desired Results
 format is a string describing the way the data is
to be printed %d display value as an integer
 data is one or more scalars or arrays %e display value in exponential form
 The format is a string containing text plus
%f display value in floating-point form
special conversion characters describing the
format of the data %g display value in either floating-point or
.exponential form, whichever is shorter
%s display value as a string
\n line feed, skip to a new line

dr.dcd.h CS 101 /SJC 5th Edition 9 dr.dcd.h CS 101 /SJC 5th Edition 10

Formatted Output: fprintf4 Formatted Output: fprintf5


 A few fprintf examples:  Advanced formatting characters
Extra Format
Descriptions
Character
+ display ’+’ sign if data is positive

– display data in a left-adjusted fashion


m display data in a field m-digits wide

m.N display data in a field m-digits wide,


.including n-digits after the decimal point
0 replaces extra blanks by zeros
 Use double % to insert a percentage sign in an
fprintf statement.  For example:
 fprintf(’%07.2f\n’, 12.345) produces ’0012.35’

dr.dcd.h CS 101 /SJC 5th Edition 11 dr.dcd.h CS 101 /SJC 5th Edition 12

2
9/4/2018

Formatted Output: fprintf6 Formatted Output: fprintf7


 Display a string in different formats:  Display a number in different formats:

dr.dcd.h CS 101 /SJC 5th Edition 13 dr.dcd.h CS 101 /SJC 5th Edition 14

ASCII ASCII2
 ASCII stands for American Standard Code  The ASCII chart:
for Information Interchange. ASCII encodes
128 characters into 7-bits. They are digits 0
to 9, letters a to z and A to Z,
punctuations, control codes, and a space.

dr.dcd.h CS 101 /SJC 5th Edition 15 dr.dcd.h CS 101 /SJC 5th Edition 16

ASCII3 Data Files


 To include West European languages an  The save command saves data from the
additional bit is added, this 8-bit code is current workspace into a disk file.
called the extended-ASCII code.  The general form of save function
 save <–ascii> filename <var_list>
 By default, the filename will be given the
extension mat.
 If no variables are specified, all variables in the
workspace will be saved.
 If option –ascii is used, the data will be saved in
an ASCII file with the exponential form.

dr.dcd.h CS 101 /SJC 5th Edition 17 dr.dcd.h CS 101 /SJC 5th Edition 18

3
9/4/2018

Data Files2 Data Files3


 The file wsav01.mat can not be opened
externally outside the MATLAB
 The file wsav02 can be opened by edit
function or notepad.

ASCII code for


‘xyz’

 Note that when the –ascii option is used,


information such as variable names and
types will be lost.

dr.dcd.h CS 101 /SJC 5th Edition 19 dr.dcd.h CS 101 /SJC 5th Edition 20

Data Files4 Data Files5


 The load command loads data from a disk  Data having different column sizes should
file into the current workspace. not be saved together if the –ascii option
 The general form of load function will be used.
 load filename
 load –mat filename.dat
 If a MAT-file is loaded, all of the variables
will be restored with the names and types.

dr.dcd.h CS 101 /SJC 5th Edition 21 dr.dcd.h CS 101 /SJC 5th Edition 22

Data Files6 Scalar Arithmetic Operations


Arithmetic
The contents of an ASCII-file will be Algebraic Form MATLAB Form
 Operation
converted into an array having the same Addition a+b a+b
name as the file (w/o the extension). Subtraction a–b a–b

 Data having different column sizes should Multiplication axb a*b


not be saved together if the –ascii option Division
a
____
a / b or b \ a
b
will be used.
Exponentiation ab a^b

 Note:
 b\a is called the left division.
 Parentheses may be used to group terms and the sub-
expressions inside the parentheses are evaluated first.

dr.dcd.h CS 101 /SJC 5th Edition 23 dr.dcd.h CS 101 /SJC 5th Edition 24

4
9/4/2018

Scalar Arithmetic Operations2 Array & Matrix Operations


Operation Syntax Descriptions
 Parentheses may be used to group terms Array Addition a+b Array addition and matrix addition are identical.
Array Subtraction a–b Array subtraction and matrix subtraction are identical.
and the sub-expressions inside the Element-by-element multiplication of a and b :
parentheses are evaluated first. Array Multiplication a .* b
a(i,j)*b(i,j). Both a and b must be the same shape.
Matrix Multiplication a*b The no. of columns in a must equal the no. of rows in b.
 For example: Element-by-element division of a and b: a(i,j)/b(i,j).
Array Right Division a ./ b
Both arrays must be the same shape.
 2^(8+6/3) returns 1024
Element-by-element division of a and b: b(i,j)/a(i,j).
Array Left Division a .\ b
 2^8+6/3 returns 258 Both arrays must be the same shape.
In MATLAB, it is defined by a*inv(b), where inv(b) is
Matrix Right Division a/b
the inverse of b.
In MATLAB, it is defined by inv(a)*b, where inv(a) is
Matrix Left Division a\b
the inverse of a.
Element-by-element exponential of a and b:
Array Exponentiation a .^ b
a(i,j)^b(i,j). Both a and b must be the same shape.

 Element-by-element operation is performed on corresponding


elements in the associated two arrays.

dr.dcd.h CS 101 /SJC 5th Edition 25 dr.dcd.h CS 101 /SJC 5th Edition 26

Array & Matrix Operations2 Precedence of Arithmetic Operations


Precedence Descriptions
 Array operation between two arrays:
Perform calculations inside all parentheses,
1
working from the innermost set to the outermost.
Perform all exponentials, working from left to
2
 Array multiplication: right.
Perform all multiplications and divisions, working
3
from left to right.
Perform all additions and subtractions, working
4
 Matrix multiplication: from left to right.

 Note:
 a^b^c is not evaluated as but (a^b)^c.

dr.dcd.h CS 101 /SJC 5th Edition 27 dr.dcd.h CS 101 /SJC 5th Edition 28

Solutions of Linear Equations Homework Assignment #4


 Consider the following system of three equations with  Quiz 2.3
three unknowns:
3x + 2y – z = 10
 Page 51: 2, 3
–x + 3y + 2z = 5  Quiz 2.4
x – y – z = –1
 Page 58: 1, 2
which can be expressed as
AX = B
 This assignment is due by next week.
 Late submission will be penalized.
where A= , B= and X= .

It can be solved for X using linear algebra. The solution is

X = A-1B =

dr.dcd.h CS 101 /SJC 5th Edition 29 dr.dcd.h CS 101 /SJC 5th Edition 30

5
9/4/2018

Common MATLAB Functions Mathematical Functions


 Mathmatical functions:  abs(x): returns |x| or the magnitude if x is a
 abs, min, max, mod, rem complex number.
 cos, sin, tan  [maximum, index]=max(x): returns the maximum
value in array x and its index.
 acos, asin, atan, atan2(y,x)
 [minimum, index]=min(x): returns the minimum
 exp, log, log10, sqrt value in array x and its index.
 Rounding functions
 ceil, floor, round, fix
 String conversion functions
 char, double, int2str, num2str, str2num

dr.dcd.h CS 101 /SJC 5th Edition 31 dr.dcd.h CS 101 /SJC 5th Edition 32

Mathematical Functions2 Mathematical Functions3


 Both mod(x,y) and rem(x,y) return the reminder  atan2(y,x): returns over 4 quadrants of angle.
after division.
 The mod function produces a result that is either
zero or has the same sign as the divisor.
 The rem function produces a result that is either
zero or has the same sign as the dividend.

dr.dcd.h CS 101 /SJC 5th Edition 33 dr.dcd.h CS 101 /SJC 5th Edition 34

Rounding Functions String Conversion Functions


 ceil(x): rounds x to the nearest integer towards .  char: converts numbers to a string.
 fix(x): rounds x to the nearest integer towards 0.  double: converts an array of char to ASCII codes.
 floor(x): rounds x to the nearest integer towards –  int2str: converts a number to an integer string.
 round(x): rounds x to the nearest integer.  num2str: converts a number to a string.
 str2num: converts a string to a number.

dr.dcd.h CS 101 /SJC 5th Edition 35 dr.dcd.h CS 101 /SJC 5th Edition 36

6
9/4/2018

Two-Dimensional Plots Two-Dimensional Plots2


 The general form of plot function
 plot(x, y)
 y is a 1-1 function of x
 When plot is execute, a figure window opens.
 Title and axis labels can be added by
 title(str)
 xlabel(str)
 ylabel(str)
 Grid lines can be enabled/disable by
 grid on/off

dr.dcd.h CS 101 /SJC 5th Edition 37 dr.dcd.h CS 101 /SJC 5th Edition 38

Save Plots Save Plots2


 The print command can be used to save a  Use File/Save As menu option on the Figure
plot as an image from a M-script Window to save a graphical image.
 print <option> filename
 Valid options
 –deps: monochrome encapsulated postscript
___ __ image
 –depsc: color encapsulated postscript image
 –djpeg: JPEG image
 –dpng: portable network graphic image
 –dtiff: compressed TIFF image

dr.dcd.h CS 101 /SJC 5th Edition 39 dr.dcd.h CS 101 /SJC 5th Edition 40

Multiple Plots Multiple Plots2


 1st method: plot two functions y1=f(x1) and
y2=g(x2) at once
 plot(x1, y1, x2, y2, …)
 x1 and x2 can be defined over different ranges
 For example:
 f(x) = sin(2x)
 The first derivation of f(x) = 2 cos(2x)
 To plot them side-by-side for comparison

dr.dcd.h CS 101 /SJC 5th Edition 41 dr.dcd.h CS 101 /SJC 5th Edition 42

7
9/4/2018

Multiple Plots3 Multiple Plots4


 2nd method: plot y1 and y2 separately with
hold function enabled
 plot(x1, y1)
 hold on: Retain current plot when adding new plots
 plot(x2, y2)
 hold off: next plot will clear up figure space first

dr.dcd.h CS 101 /SJC 5th Edition 43 dr.dcd.h CS 101 /SJC 5th Edition 44

Graph Properties Graph Properties2


Line Style Indicator Marker Style Indicator Color Indicator

 You can change the appearance of your solid - point . blue b


dotted : circle o green g
plots by selecting user defined dash-dot -. x-mark x red r
 line styles dashed -- plus + cyan c
 color (none) (no line) star * magenta m
square s yellow y
 mark styles.
diamond d black k
 Legends can be added by
triangle down v
 legend(str1, str2, …, <position>)
triangle up ^
 Position: Best – least conflict with the figure
triangle left <
NorthWest North NorthEast
triangle right >
West East
pentagram p
SouthWest South SouthEast
hexagram h

dr.dcd.h CS 101 /SJC 5th Edition 45 dr.dcd.h CS 101 /SJC 5th Edition 46

Specify Graph Property Specify Graph Property2


 plot(x, y, opstr)
 Opstr combining line style, marker style, and
color
 For example: ’:ok’ indicates dotted line ’:’, circle
marker ’o’, and black color ’k’.
 legend(str_list, ’Location’, ’Best’)
 Best – least conflict with the figure
 All locations can be outside plot, eg. ’BestOutside’

dr.dcd.h CS 101 /SJC 5th Edition 47 dr.dcd.h CS 101 /SJC 5th Edition 48

8
9/4/2018

Specify Graph Property3 Logarithmic Plots


 A logarithmic scale (base 10) is useful if a
variable ranges over many orders of
magnitude, or data varies exponentially.
 semilogy – uses a log10 scale on the y axis
 semilogx – uses a log10 scale on the x axis
 loglog – uses a log10 scale on both axes

dr.dcd.h CS 101 /SJC 5th Edition 49 dr.dcd.h CS 101 /SJC 5th Edition 50

Logarithmic Plots2 Logarithmic Plots3

dr.dcd.h CS 101 /SJC 5th Edition 51 dr.dcd.h CS 101 /SJC 5th Edition 52

Example 2.4 Example 2.42


 Figure below shows a voltage source V=120 Volt  The power supplied to the load RL is given by
with an internal resistance RS of 50 W supplying a PL = I2 RL
load of resistance of RL. Find the value of load where I is the current supplied to the load, it can be
resistance that will result in the maximum possible obtained by Ohm’s law
power being supplies by the source to the load. Plot V
_______
the power supplied to the load as a function of RL. RS+RL
 Procedures to perform the work:
 Define an array of possible values for RL
 Compute the current for each value of RL
 Compute the supplied power for each value of RL
 Plot the power supplied to the load for each value of RL
 Determine the maximum power

dr.dcd.h CS 101 /SJC 5th Edition 53 dr.dcd.h CS 101 /SJC 5th Edition 54

9
9/4/2018

Example 2.43 Example 2.44

dr.dcd.h CS 101 /SJC 5th Edition 55 dr.dcd.h CS 101 /SJC 5th Edition 56

Homework Assignment #5
 2.15 Exercises
 Page 83: 2.1 - 2.8
 This assignment is due by next week.
 Late submission will be penalized.

dr.dcd.h CS 101 /SJC 5th Edition 57

10
Chapter 3
Two-Dimensional Plots

dr.dcd.h CS 101 /SJC 5th Edition 1


Logarithmic Scales
 Some time data in logarithmic scale can
have linear property.
 semilogy – uses a log10 scale on the y axis
 semilogx – uses a log10 scale on the x axis
 loglog – uses a log10 scale on both axes

dr.dcd.h CS 101 /SJC 5th Edition 2


Logarithmic Scales2

dr.dcd.h CS 101 /SJC 5th Edition 3


Logarithmic Scales3

dr.dcd.h CS 101 /SJC 5th Edition 4


Controlling Axis
Command Descriptions
axis Returns axis limits: [xmin, xmax, ymin, ymax].
axis(x) Sets axis limits to x, a 1x4 vector.
axis equal Sets the aspect ratio to be equal on both axes.
Same as axis equal except that the axis box fits
axis image
tightly around the data.
axis square Makes the current axis box square.
axis normal Cancels the effect of axis equal and axis square
axis auto Returns the axis scaling to its default.
axis on/off Turns on/off axis labeling, tick marks.

dr.dcd.h CS 101 /SJC 5th Edition 5


Controlling Axis2

dr.dcd.h CS 101 /SJC 5th Edition 6


Controlling Axis3

dr.dcd.h CS 101 /SJC 5th Edition 7


Controlling Axis4

dr.dcd.h CS 101 /SJC 5th Edition 8


Controlling Axis5

dr.dcd.h CS 101 /SJC 5th Edition 9


Controlling Axis6

dr.dcd.h CS 101 /SJC 5th Edition 10


Creating Multiple Plots by hold
 Multiple plots on the same axes by use hold
on/off to enable and disable overwriting

dr.dcd.h CS 101 /SJC 5th Edition 11


Creating Multiple Plots by figure
 Creating multiple figure windows by using
figure(figure_id) to create a new figure.
 gcf returns the figure_id

dr.dcd.h CS 101 /SJC 5th Edition 12


Creating Multiple Plots by subplot
 Multiple plots by using subplot(m,n,p) to
divide the current figure into an m-by-n
grid and creates a subplot in the position
specified by p.
 Frame id is assigned in a row-order.

dr.dcd.h CS 101 /SJC 5th Edition 13


Creating Multiple Plots by subplot2
 Subplot frames can have different sizes as
long as they are not overlaid.

dr.dcd.h CS 101 /SJC 5th Edition 14


Creating Multiple Plots by subplot3
 Multiple plots by using subplot(row, col, n)
to place at the nth sub-axes in a row-by-col
grid.

dr.dcd.h CS 101 /SJC 5th Edition 15


Specially Spaced Data
 Operators that produce equally-spaced
samples:
 first:incr:last
 linspace(first,last,n)
 Operator that produces logarithmic spacing
samples:
 logspace(first,last,n)
 If n is not specified then 50 equally-spaced
samples are producred. i.e.
logspace(first,last)=linspace(first,last,50)

dr.dcd.h CS 101 /SJC 5th Edition 16


Example 3.1
 Show y=x2-10x+25 over the range [0,10] in
different scales.

dr.dcd.h CS 101 /SJC 5th Edition 17


Enhanced Lines
 Properties of a plotted line can be set by
plot(x,y,’PropertyName’,value, …)
4 properties associated with plotted line
 LineWidth
 MarkerSize
 MarkerFaceColor
 MarkerEdgeColor
 For example:
 plot(x,y,’LineWidth’,3,’MarkerSize’,3)

dr.dcd.h CS 101 /SJC 5th Edition 18


Enhanced Lines2

dr.dcd.h CS 101 /SJC 5th Edition 19


Enhanced Text Strings
 Use stream modifiers to enhance text
strings (titles, labels, etc.) such as bold
face, italics, and special symbols.
 Common stream modifiers:
 \bf, \it – bold face, italics
 \rm – remove modifiers
 \fontname{name} – specify font name
 \fontsize{size} – specify font size
 _{txt} – specify txt as a subscript
 ^{txt} - specify txt as a superscript
 \color{color} – specify text color

dr.dcd.h CS 101 /SJC 5th Edition 20


Enhanced Text Strings2
Character Greek Character Greek Character Mathmetic
Sequence Symbol Sequence Symbol Sequence Symbol
\alpha a \int

\beta b \cong
\gamma g \Gamma G \sim
\delta d \Delta D \infty
\epsilon e \pm
\eta h \leq
\theta q \geq
\lambda l \Lambda L \neq
\mu m \propto
\nu n \div
\pi p \Pi P \circ
\phi f \leftrightarrow
\rho r \leftarrow
\sigma s \Sigma S \rightarrow
\tau t \uparrow
\omega w \Omega W \downarrow
dr.dcd.h CS 101 /SJC 5th Edition 21
Enhanced Text Strings3
 For example: the following expression
'\fontsize{18}\color{blue}\int_{\Omega}
\color{green}\int_{\Gamma}
\color{black}(\nu^{2}+3\nu\mu)
\color{red}d\nud\mu'
Produces the following text:

dr.dcd.h CS 101 /SJC 5th Edition 22


Place Random Text
 A text string can be randomly placed by:
 text(x, y, string, <modifiers>)
 Position modifiers are used to specify
alignment:
 HorizontalAligment: Left/Center/Right
 VerticalAlignment: Top/Middle/Bottom
 For example:
text(2,1.4,'\omega \color{red}abc\rm',…
'HorizontalAlignment', 'Center')

dr.dcd.h CS 101 /SJC 5th Edition 23


Example 3.2
 Plot function y(t)=10 e-t/t sin(wt) over [0,10]

dr.dcd.h CS 101 /SJC 5th Edition 24


Homework Assignment #6
 3.7 Exercises
 Page 123: 3.1, 3.6, 3.11, 3.12
 This assignment is due by next week.
 Late submission will be penalized.

dr.dcd.h CS 101 /SJC 5th Edition 25


Polar Plots
 Polar is a special plotting function, which
plots data in polar coordinates.
 The general form of polar function
 polar(x, y)
 Data in frequency domain using polar plots
have a better illustration than by using
linear plots.

dr.dcd.h CS 101 /SJC 5th Edition 26


Example 3.2 Refreshed
 Plot function y(t)=10 e-t/t sin(wt) over [0,10]

dr.dcd.h CS 101 /SJC 5th Edition 27


Example 3.2 Refreshed2
 Polar plot function y(t)=10 e-t/t sin(wt) over [0,10]

dr.dcd.h CS 101 /SJC 5th Edition 28


Example 3.3
 Plot gain of a cardioid microphone 2g cos(q)

dr.dcd.h CS 101 /SJC 5th Edition 29


Additional Plotting Functions
Function Descriptions
bar Creates a vertical bar plot.
barh Creates a horizontal bar plot
stairs Creates a stair plot
stem Creates a vertical bar plot
Creates a polar plot with an arrow drawn from the
compass
origin to the location of each point
pie Creates a pie bar plot. This function determines the
percentage of each item.

 If pie(p, q) syntax is used, q is called an explode


array which controls whether individual pie slices are
separated from the rest of the pie.

dr.dcd.h CS 101 /SJC 5th Edition 30


Additional Plotting Functions2
 To create multiple-bar chart, data needs to be
arranged in column major order.

dr.dcd.h CS 101 /SJC 5th Edition 31


Additional Plotting Functions3
 Basically, stairs plots are the envelopes of the bar
charts.

dr.dcd.h CS 101 /SJC 5th Edition 32


Additional Plotting Functions4
 Basically, stem plots can be considered as narrowed
bar charts.

dr.dcd.h CS 101 /SJC 5th Edition 33


Additional Plotting Functions5
 The points to compass plot are in Cartesian coord.,
not in polar form.

dr.dcd.h CS 101 /SJC 5th Edition 34


Additional Plotting Functions6
 If pie(p, q) syntax is used, q is called an explode
array which controls whether individual slices are
separated from the pie.

dr.dcd.h CS 101 /SJC 5th Edition 35


Homework Assignment #7
 Quiz 3.1
 Page 114: 7
 3.7 Exercises
 Page 123: 3.5, 3.14
 This assignment is due by next week.
 Late submission will be penalized.

dr.dcd.h CS 101 /SJC 5th Edition 36


Chapter 4
Branching Statement
& Program Design

dr.dcd.h CS 101 /SJC 5th Edition 1


Top-Down Design
 It starts with a large task and breaks it
down into smaller sub-tasks. Each sub-task
may in turn be subdivided into even smaller
building-blocks if needed.
 Each building-block can be coded and
tested independently.
 Once all the building blocks have been
verified to work properly, we combine the
sub-tasks into a complete project.
 This is as known as divide and conquer.

dr.dcd.h CS 101 /SJC 5th Edition 2


Top-Down Design2

2 G11
G1
G12
1 3
G2
G 2 G31
G3 G32
4
3
G4

Divide and Conquer

dr.dcd.h CS 101 /SJC 5th Edition 3


Program Design Process
Start

Define the problem

Define required
inputs and outputs Decomposition

Design the method


Stepwise
Convert method into refinement
MATLAB statements
Top-down design
Test the resulting process
MATLAB program

End

dr.dcd.h CS 101 /SJC 5th Edition 4


Program Testing Process
Start

Unit testing of
individual subtasks

Subtasks validated separately

Add subtasks into Repeat as many


the main program times as needed

Combined subtasks into one unit

Repeat as many
Alpha release times as needed

Major bugs fixed

Repeat as many
Beta release times as needed

Minor bugs fixed


End

dr.dcd.h CS 101 /SJC 5th Edition 5


Pseudo-Code
 To implement an algorithm, it should be
described in a understandable form. The
descriptions are called constructs.
 Each construct can be described in a special
way called pseudocode.
 Pseudocode should describe the project in
plain English, with a separate line for each
distinct idea or segments of MATLAB code.
For example:
Convert degree in Fahrenheit (F) to degree in Kelvins
(K) by (F-32)*5/9+273.15

dr.dcd.h CS 101 /SJC 5th Edition 6


True or False
 The logical data type is used to represent
two possible concept called logical values,
true or false.
 Both logical values can be produced by
functions true and false
 true returns 1
 false returns 0

dr.dcd.h CS 101 /SJC 5th Edition 7


True or False2
 Logical values are stored in a single byte of
memory.
 In an expression, zero represents false
while non-zero represents true.

dr.dcd.h CS 101 /SJC 5th Edition 8


More Operators
 Relational operators are operators that
compare two numbers and produce a true
or false.
 Logic operators are operators that
compare one or two numbers and produce
a true or false.
 General form of a operation op between
the results of two expressions e1 and e2:
 e1 op e2

dr.dcd.h CS 101 /SJC 5th Edition 9


Relational Operators
Operator Operation
== equal to
~= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to

 Notice:
 == is a comparison operator.
 = is an assignment operator.

dr.dcd.h CS 101 /SJC 5th Edition 10


Relational Operators2
 Relational operators are element-by-
element operations. For example:

 If one of the operand is a scalar, then the


scalar will be used to compare each
element of the array. For example:
 ’test’ > ’k’ produces 1 0 1 1
 A string is an array of characters.

dr.dcd.h CS 101 /SJC 5th Edition 11


Roundoff Errors
 Due to roundoff errors during computer
calculations, two theoretically equal
numbers can differ slightly, causing an
equality or inequality test to fail.
 For example:
 sin(pi) and sin(p)

dr.dcd.h CS 101 /SJC 5th Edition 12


Logical Operators
Operator Operation
& logical AND
&& logical AND with shortcut evaluation
| logical OR
|| logical OR with shortcut evaluation
xor logical exclusive OR
~ logical NOT

 The general form of a logical operation is


 exp1 op exp2
 Note that && and || are scalar operators

dr.dcd.h CS 101 /SJC 5th Edition 13


Logical ANDs
 The result of an AND operator is true if and
only if both operands are true.
 If at least one of the operands is false, the
result is false.
 && is an AND operator supports short-cut
evaluations; i.e.
 && will returns a false if exp1 is false.
 In contrast, & always evaluates both exp1 and
exp2 before returning an answer.

dr.dcd.h CS 101 /SJC 5th Edition 14


Logical ORs
 The result of an OR operator is true if at
least one of the operands is true.
 If both operands are false, the result is
false.
 || is an OR operator supports short-cut
evaluations; i.e.
 || will returns a true if exp1 is true.
 In contrast, | always evaluates both exp1 and
exp2 before returning an answer.

dr.dcd.h CS 101 /SJC 5th Edition 15


Logical Exclusive ORs
 The result of a XOR operator is true if and
only if one operand is true and the other is
false.

dr.dcd.h CS 101 /SJC 5th Edition 16


Truth Table
 Truth Table for Logical Operators
inputs and or xor not
e1 e2 e1&e2 e1&&e2 e1|e2 e1||e2 xor(e1,e2) ~e1
F F F F F F F T
F T F F T T T T
T F F F T T T F
T T T T T T F F

dr.dcd.h CS 101 /SJC 5th Edition 17


Hierarchy of Operations
Precedence Descriptions
All arithmetic operators are evaluated in the order
1
of previously described in Chapter 2.
All relational operators (==, ~=, >, >=, <, <=)
2
are evaluated, working from left to right.
3 All ~ operators are evaluated.
All & and && operators are evaluated, working
4
from left to right.
All |, || and XOR operators are evaluated,
5
working from left to right.

 For example:
 5>3 == 5>3 produces 0
 5>3 == 5<3 produces 1

dr.dcd.h CS 101 /SJC 5th Edition 18


Hierarchy of Operations2
 It is important to follow the precedence to
evaluate the outcome. You will be surprised
if you only exam the expression by your
instinct.
 For example:
 5>3 == 5>3 produces 0
 5>3 == 5<3 produces 1

dr.dcd.h CS 101 /SJC 5th Edition 19


Logical Functions
function Descriptions
ischar(x) Returns true if x is a character array.
isempty(x) Returns true if x is an empty array.
isinf(x) Returns true if x is Inf (infinite).
isnan(x) Returns true if x is a NaN (not-a-number).
isnumeric(x) Returns true if x is a numeric array.
logical(x) Convert numerical value x to logical value.

 For all the data shown above only characters are not
considered as numeric.

dr.dcd.h CS 101 /SJC 5th Edition 20


Homework Assignment #8
 Quiz 3.1
 Page 103: 1-21
 This assignment is due by 03/05.
 Late submission will not be accepted.

dr.dcd.h CS 101 /SJC 5th Edition 21


Flowchart
 Flowcharts use special shapes to show
different types of steps in a process.

dr.dcd.h CS 101 /SJC 5th Edition 22


Branches
 Branches are statements that allow us to
select and execute specified sections of
code (called blocks) while skipping other
sections of code.
 Three constructs of branches:
 if
 switch
 try-catch

dr.dcd.h CS 101 /SJC 5th Edition 23


if Statement
 The if construct has the form
if comparison1
statements_block1
elseif comparison2
statements_block2
else
statements_block3
end

 where comparisons are logical expressions that


control the operation of the if construct.

dr.dcd.h CS 101 /SJC 5th Edition 24


if Statement2

 There can be any number of elseif clause


(0 or more), but there can be at most one
else clause.

dr.dcd.h CS 101 /SJC 5th Edition 25


Exercise 1
 The quadratic equation
 1. State the problem:
Write a program to solve for the roots of a
quadratic equation, ax2+bx+c=0.
 2. Define the inputs and outputs:
Inputs will be the coefficients a, b, and c.
Outputs will be the roots of equations
 3. Define the solution:

dr.dcd.h CS 101 /SJC 5th Edition 26


Exercise 12
 Computational example
 4. Evaluate the discriminant function:

 5. If >0, then there are 2 distinct real roots.


If =0, then there is a single repeated root.
If <0, then there are 2 complex roots.

dr.dcd.h CS 101 /SJC 5th Edition 27


Exercise 13

dr.dcd.h CS 101 /SJC 5th Edition 28


Exercise 2
 Function of two variables
 1. State the problem:
Evaluate function f(x,y) which is defined as:

 2. Define the inputs and outputs:


Inputs are values of x and y.
Outputs are f(x,y)
 3. Evaluate f(x,y) based on 4-branched if

dr.dcd.h CS 101 /SJC 5th Edition 29


Exercise 22

dr.dcd.h CS 101 /SJC 5th Edition 30


Nested if Statement
 Two if constructs are said to be nested if
one of them is embed in another if block.
 It can be done by breaking the keyword
elseif to else; if.
if comparison1
statements_block1
if comparison2
statements_block2

end
else
statements_block4
end

dr.dcd.h CS 101 /SJC 5th Edition 31


Exercise 3
 Assigning Letter Grades
 State the problem:
Reads a numerical grade and assigns a letter
grade in according to the following chart:

A: 94 < grade
B: 74 < grade < 95
C: 64 < grade < 75
D: 44 < grade < 65
F: 0 < grade < 45

dr.dcd.h CS 101 /SJC 5th Edition 32


Exercise 32

dr.dcd.h CS 101 /SJC 5th Edition 33


switch Statement
 The switch construct has the form
switch ctrl_expr
case case_expr1
statement_block1
case case_expr2
statement_block2

otherwise
statement_block3
end
 If the value of ctrl_expr is equal to the first
case_expr, then the first block will be executed
and the program will jump to the first statement
following end.

dr.dcd.h CS 101 /SJC 5th Edition 34


switch Statement2
 The ctrl_expr and case_expr may be
numeric or string values.
 If more than one case_expr should cause
the same code to execute, then a combo
case can be used.
case {case_1, case_2, …}

dr.dcd.h CS 101 /SJC 5th Edition 35


switch Statement3
 The switch construct is another form of
using cascaded if constructs.

if ctrl ==case1
statements_block1
elseif ctrl ==case2
statements_block2

else
statements_block3
end

dr.dcd.h CS 101 /SJC 5th Edition 36


switch Statement4
 If-statements and switch-statements are
similar and sometimes interchangeable.
 switch val; case {1, 5, 7, 8}
 If (mod(val,2)==1)
 Both switch and if have their own strong and
weak points.

dr.dcd.h CS 101 /SJC 5th Edition 37


try-catch Statement
 The try/catch construct is designed to
trap errors.
 The try-catch construct has the form
try
statement_block1
catch
statement_block2
end

 If an error occurs in the try block, then instead of


aborting the execution, the code in the catch
section will be executed.

dr.dcd.h CS 101 /SJC 5th Edition 38


try-catch Statement2
 Fatal errors or critical exceptions will be
caught by try-catch construct. Such as:
 access to undefined variables

 array indexing overflow

 failed to open a file

dr.dcd.h CS 101 /SJC 5th Edition 39


try-catch Statement3

dr.dcd.h CS 101 /SJC 5th Edition 40


Example 4.5: Low Pass Filter
 Given a RC low pass filter:

 Vi is the sinusoidal input voltage of frequency f,


R is a resistor in ohms, C is a capacitor in farads.
 Evaluate the ratio of the output Vo to the input Vi

(4.3)

dr.dcd.h CS 101 /SJC 5th Edition 41


Example 4.52
 Plot the amplitude and frequency response of this
filter over the frequency range 0 f 1000Hz as
R=16kW and C=1mF.
 Equ. (4.3) indicates that the ratio x is a complex
number, so the amplitude and the phase can be
computed as = abs(x) and angle(x).
 Since the response can vary over a wide range,
therefore we will use a loglog plot for the
amplitude response and a semilogx plot for the
phase response.

dr.dcd.h CS 101 /SJC 5th Edition 42


Example 4.53
 Plot the amplitude and frequency response of this
filter over the frequency f of the output Vo to the
input Vi

dr.dcd.h CS 101 /SJC 5th Edition 43


Example 4.6: Ideal Gas Law
 An ideal gas is defined as one in which all
collisions between molecules are perfectly
elastic; i.e. no kinetic energy lost.
 The Ideal Gas Law:

 R is 8314 L kPa/mol K
 At T=273 K, n=1 mole, estimate V as P varies
from 1 to 1000 kPa and plot P versus V.

dr.dcd.h CS 101 /SJC 5th Edition 44


Example 4.62
 Then T is increased to 373 K. Plot P versus V.

dr.dcd.h CS 101 /SJC 5th Edition 45


Homework Assignment #9
 4.7 Exercises
 Page 169: 4.1, 4.4, 4.5, 4.14
 This homework is due by next week.
 Late submission will be penalized.

dr.dcd.h CS 101 /SJC 5th Edition 46


Chapter 5
Loops & Vectorization

dr.dcd.h CS 101 /SJC 5th Edition 1


Loops
 Loop construct permits user to execute a
block of instructions more than once.
 Base on how the repetition is controlled,
there is two basic forms of loops:
 while loops
 repeat an indefinite number of times until a user-
specified condition is satisfied
 for loops
 repeat a pre-determined number of times

dr.dcd.h CS 101 /SJC 5th Edition 2


Vectorization
 Vectorization is an alternative way to
perform repeated instructions, and it is
faster than using loops.
 Basically, it is using array and matrix
operators to replace sequences of iterations.

dr.dcd.h CS 101 /SJC 5th Edition 3


while Loop
 There are two types of while loop
 while loop (or called repeat until loop)
 do-while loop (MATLAB didn’t support this)

dr.dcd.h CS 101 /SJC 5th Edition 4


while Loop2
 The general form of a while loop
while expression
statement_block
end

 If the controlling expression returns true, the


inner statements will be executed.
 The process will be repeated until the expression
becomes false.

controlling fals
expression e

true
Statements
Update

dr.dcd.h CS 101 /SJC 5th Edition 5


Example 5.1: Statistical Analysis
 Statistical Analysis
 1. State the problem:
 The average or arithmetic mean of a set of
numbers is defined as

 Wand the standard deviation s is

dr.dcd.h CS 101 /SJC 5th Edition 6


Example 5.1: Statistical Analysis2
 2. Define the inputs and outputs::
 Reads in a set of numbers and computes the
mean and the standard deviation.
 3. Define the algorithm:
 Use a while loop to read a set of numbers
 Computer the mean
 Compute the variance and the standard deviation
is its square-root

dr.dcd.h CS 101 /SJC 5th Edition 7


Example: Statistical Analysis2

dr.dcd.h CS 101 /SJC 5th Edition 8


for Loop
 The general form of a for loop
for index=expr
statement_block
end

 Variable index is the iteration counter and the


output of expr should be an array.
 No. of iterations matches the size of columns.
 For the nth iteration, the index was assigned the
nth column of the array.

index isn’t false


exceeded

true
Statements
Index++

dr.dcd.h CS 101 /SJC 5th Edition 9


for Loop2
 The index can be set as
 output from a colon operation: (e.g. [3:2:17])
 output from a function: (e.g. linspace(2,3, 5))
 a set of numbers, (e.g. [5 9 7])
 a matrix (e.g. [1 2 3; 4 5 6])

dr.dcd.h CS 101 /SJC 5th Edition 10


for Loop3
 If the index array was modified during the
execution of loop, the number of iteration
will not be affected. However, the loop
outcomes may be affected.

dr.dcd.h CS 101 /SJC 5th Edition 11


Example 5.2: Factorial Function
 Statistical Analysis
 1. State the problem::
 The factorial function is defined as

 2. Define the algorithm:


 With 0!=1.

dr.dcd.h CS 101 /SJC 5th Edition 12


Example 5.2: Factorial Function2

dr.dcd.h CS 101 /SJC 5th Edition 13


Example 5.3: Date of the Year
 Date of the Year
 1. State the problem:
 Write a MATLAB script that accept a day and a
year, then calculate the month, day, and
weekday corresponding to the given date.
 2. Define the algorithm:
 We need a reference, say Sat. 12/31/1904.
 1904 was a leap year and any day after that day
starts at the first day of the week, a Sunday.
 Find the total day from the reference to the
target day, and then the reminder of 7 days is
the weekday.

dr.dcd.h CS 101 /SJC 5th Edition 14


Example 5.3: Day of the Year2

dr.dcd.h CS 101 /SJC 5th Edition 15


Example 5.3: Day of the Year3

dr.dcd.h CS 101 /SJC 5th Edition 16


Practical Tips
 Indent the bodies of loops. It makes the
code much more readable.
 Pre-allocating arrays. Evan though it is
easy to extend an existing array:
 If a=1:4 and then a(8)=3 will result in
a=[1 2 3 4 0 0 0 3].
 Internally, MATLAB did some extra work:
 Create a new array tmp;
 Copy the contents of a to tmp;
 Add the new value to the last element in tmp;
 Delete a and rename tmp as a.

dr.dcd.h CS 101 /SJC 5th Edition 17


Vectorization
 Operations performed over vectors are
faster than those over loops
 Comparing loops and vectorization:
 To initialize a 1xn vector and then computer
squares of this vector for m times.
 Use loop without initializing the array;
 Use loop with pre-allocated array;
 Use vectorization.
 Use tic function to set a build-in elapsed time
counter, and toc function returns the elapsed
time in seconds since the last call to function tic .

dr.dcd.h CS 101 /SJC 5th Edition 18


Vectorization2

dr.dcd.h CS 101 /SJC 5th Edition 19


Vectorization3

dr.dcd.h CS 101 /SJC 5th Edition 20


Break and Continue
 Statements to control the flow of loops:
 break causes the loop to terminate prematurely.
 continue causes the loop to skip a pass, but
continue on the rest of the loop
 both are used in conjunction with an if statement
 Note that if the break or continue is used in a
nested loops then it terminates or skips the
current loop only.

dr.dcd.h CS 101 /SJC 5th Edition 21


Example: continue

dr.dcd.h CS 101 /SJC 5th Edition 22


Example: break

dr.dcd.h CS 101 /SJC 5th Edition 23


Nested Loops
 If one loop is completely inside another
one, the two loops are called nested loops.
 Each loop in nested loops should have a
distinctive loop index variable.
 When MATLAB encounters an
end or a break statement, it
associates the statement with
the innermost currently
executing for loop construct.

dr.dcd.h CS 101 /SJC 5th Edition 24


Example: Multiple Table

dr.dcd.h CS 101 /SJC 5th Edition 25


Logical Arrays
 Logical data has one of two possible values:
true (1) or false (0).
 Scalars and arrays of logical data are
created as the output of relational and logic
operators.

dr.dcd.h CS 101 /SJC 5th Edition 26


Logical Mask
 Logical arrays can serve as a mask for
arithmetic operations.
 A mask is an array that selects the
elements of another array for use in an
operation.
 For example:
 Take the square of all the elements that are odd
numbers.

dr.dcd.h CS 101 /SJC 5th Edition 27


Logical Mask & Vectorization
 For example:
 Take the square root of all the elements that are
greater than 5. Two approaches: by using
 either if construct in a for loop construct
 or a logical mask.

dr.dcd.h CS 101 /SJC 5th Edition 28


Logical Mask & Vectorization2

dr.dcd.h CS 101 /SJC 5th Edition 29


Homework Assignment #10
 Quiz 5.1
 Page 198: 6-10
 This homework is due by next week.
 Late submission will be penalized.

dr.dcd.h CS 101 /SJC 5th Edition 30


MATLAB Profile
 MATLAB profile can be used to identify the
parts of a program that consume the most
execution time.
 Profile can be started by selecting the Run
and Time button from the Editor window.
 Or use ’profile on’ in command window
before running a program, then use ’profile
viewer’ to show the profile window.

dr.dcd.h CS 101 /SJC 5th Edition 31


MATLAB Profile2

dr.dcd.h CS 101 /SJC 5th Edition 32


MATLAB Profile3

dr.dcd.h CS 101 /SJC 5th Edition 33


Noisy Measurements
 It is known fact that we can never make
perfect measurements from a science
experiment.
 It means that the measurements always
include some noise.
 In order to estimate the theoretical
relationship, a method of linear regression
is used.
 Given a noisy set of measurements, we can
find a line y=mx+b to best fit the data.

dr.dcd.h CS 101 /SJC 5th Edition 34


Noisy Measurements2
 A standard method for finding the
regression coefficients m and b is the
method of least squares.
 The slope of the least-squares line is given by

 The intercept of the least-squares line is given by

dr.dcd.h CS 101 /SJC 5th Edition 35


Example 5.6
 Write a program to compute the least-
squares slope m and y-axis intercept b for a
given set of noisy measured points (x, y).

dr.dcd.h CS 101 /SJC 5th Edition 36


Example 4.62

dr.dcd.h CS 101 /SJC 5th Edition 37


Example 4.7
 Assume that a ball is thrown with a initial
velocity n0 at an angle of q degree. Write a
program to plot the trajectory of the ball.
 Determine the horizontal distance travelled
before it hits the ground.
 Plot the trajectories of the ball for all angles from
5 to 85o in 10o steps.
 Determine the angle that maximizes the range of
the ball.

dr.dcd.h CS 101 /SJC 5th Edition 38


Example 4.72
 Physics analysis
 If t is the time the ball will remain in the air, then
x(t) = x0 + n0 cosq t
y(t) = y0 + n0 sinq t + 1/2 g t2
with y0=0, we have the ball at ground again at
t = 2 n0 sinq / g
 With x0=0,
x(q) = 2 n02 cosq sinq / g = K0 sin(2q)
d/dq x = 2 K0 cos(2q).
Theoretically, the max happens at q=45o

dr.dcd.h CS 101 /SJC 5th Edition 39


Example 4.73

dr.dcd.h CS 101 /SJC 5th Edition 40


The textread function
 It is more convenience to read large
amount of data from a file.
 The textread function reads ASCII files
that are formatted into columns of data,
where each column can be of a different
type, and stores the contents of each
column in a separate output array.
 The syntax: [x,y,…]=textread(fname, fmt,[n])
 Format examples: ‘%s’ or ‘%f %d’

dr.dcd.h CS 101 /SJC 5th Edition 41


The textread function2
 Example: to read the contents of a file
named as ‘tst-data.txt’.

dr.dcd.h CS 101 /SJC 5th Edition 42


Homework Assignment #11
 5.8 Exercises
 Page 220: 5.1, 5.3, 5.7, 5.8, 5.9, 5.23
 This homework is due by the next week.
 Late submission will be penalized.

dr.dcd.h CS 101 /SJC 5th Edition 43


Chapter 6
User-Defined Functions

dr.dcd.h CS 101 /SJC 5th Edition 1


MATLAB Functions
 M-files are collections of MATLAB
statements that stored in a file, called a
script file.
 Script files share the command window’s
workspace, so any variables created by the
script files remain in the workspace after
the script file finishes executing.
 A script file has no input arguments returns
no results, but they communicate through
the data left behind in the workspace.

dr.dcd.h CS 101 Spring 2009 2


MATLAB Functions2
 A MATLAB function is a special type of M-
file that runs in its own independent
workspace.
 A MATLAB function receives input data
through an input argument list and returns
results to the caller through an output
argument list.
 A MATLAB function should be placed in a
file with the same name as the function
with an extension of “.m”.

dr.dcd.h CS 101 Spring 2009 3


MATLAB Functions3
 A function consists of three components
 For example:

a = cos(x)

function input argument


output argument
name

 All functions, whether they are build-in or


user-defined functions, are available for
any M-file programs

dr.dcd.h CS 101 Spring 2009 4


Syntax
 The general form of a function as
function [outarg1, outarg2, …] =
________funcName(inarg1, inarg2, …)
% H1
% other comments
Function statements
(return/end)

 The function keyword marks the beginning of


the function.
 If there are only one output argument, the
brackets can be dropped.
 Input arguments are placeholders for values.

dr.dcd.h CS 101 Spring 2009 5


Syntax2
 The comments block following the function
statement is called the help block. The first line
of it is called the H1. It should contain a one-line
summary of the purpose of the function.
 H1 will be searched and displaced by lookfor,
while the whole help block will be displaced if the
command ’help keyword’ is used.
 Execution begins at the top and ends when either
a return , an end, or the end of the function is
reached.

dr.dcd.h CS 101 Spring 2009 6


Syntax3
 For debugging purpose, it may be useful to print
intermediate results to the command window.
 However, once you complete your debugging
make sure that all your output is suppressed. If
you don’t, you’ll see extraneous information in
the command window.
 It means that you should use ’;’ at the end of
every statement.

dr.dcd.h CS 101 Spring 2009 7


Pass-by-Value
 When a function is called, MATLAB makes a
copy of the actual arguments and passes
them to the workspace of the function. If
the passed arguments are modified, it
won’t affect the original data in the caller.
Function abc’s workspace
Command window’s workspace function out=abc(in)
x = 5; …
cw.x abc.x …
… …
a = abc(x)
… abc.in abc.x

dr.dcd.h CS 101 Spring 2009 8


Local Variables
 Variables defined in an M-file function, only
have meaning inside that program.
 The only way to communicate between
functions and the workspace, is through the
function input and output arguments.

dr.dcd.h CS 101 Spring 2009 9


Example 1: dist2(x1,y1,x2,y2)
 The distance between two points (x1, y1) and (x2,
y2) can be defined as

dr.dcd.h CS 101 Spring 2009 10


H1 & Help Block
 After applying help and lookfor, function dist2
provides the following results.

dr.dcd.h CS 101 Spring 2009 11


Example 2: [x,y]=polar2rect(r,q)
 Convert polar coordinates (r,q) to rectangular form
(x,y) .

dr.dcd.h CS 101 Spring 2009 12


Example 3: [r,q]=rect2polar(x,y)
 Convert rectangular coordinates (x,y) to polar form
(r,q).

dr.dcd.h CS 101 Spring 2009 13


Example 4: Selection Sort
 State the problem. Sort the data into ascending or
descending order using the selection sort algorithm.
 Define the input/output. The inputs are typed by
the user, and the outputs are the sorted data
written to the command window.
 Describe the algorithm.
- Input an array of n values;
- Set the index i equals to1;
- Scan and locate the i-th minimum value;
- Swap the i-th minimum with the i-th element;
- repeat n-1 times.

dr.dcd.h CS 101 Spring 2009 14


Example 4: Selection Sort2

dr.dcd.h CS 101 Spring 2009 15


Optional Arguments
 Some function may support arbitrary numbers
of arguments. For example:
 plot(x, y);
 plot(x, y, ’:ok’);
 Plot(x, y, ‘’:ok’, ’MarkerSize’, 3);
 Functions that can be used to furnish optional
arguments
 nargin, nargout, nargchk
 varargin, varargout
 error, warning
 inputname

dr.dcd.h CS 101 Spring 2009 16


Optional Arguments2
 nargin: the number of actual input arguments.
 nargout: the number of actual output
arguments.
 nargchk: this function returns an error
message if too few or too many arguments are
used.
- syntax: nargchk(min, max, nargin)
 varargin: the list of variables for actual input
arguments.
 varargout: the list of variables for actual
output arguments.

dr.dcd.h CS 101 Spring 2009 17


Optional Arguments3
 error: display an error message and abort if a
fatal error was caught when a function is called.
If its input argument is an empty string, then it
does nothing.
 warning: display a warning message and
resume the execution of a function.
 inputname: this function returns the actual
name of the dummy argument.

dr.dcd.h CS 101 Spring 2009 18


Optional Arguments4

dr.dcd.h CS 101 Spring 2009 19


Homework Assignment #12
 Quiz 6.1
 Page 251: 6, 7
 This assignment is due by the next week.
 Late submission will be penalized.

dr.dcd.h CS 101 Spring 2009 20


Global Memory
 MATLAB functions can also exchange data with
each other with the base workspace through
global memory.
 Global memory is a specifal type of memory
that can be accessed from any workspace.
 A global variable is declared as
 global variable
 The default value for a global variable is empty,
so an initialization is required.

dr.dcd.h CS 101 Spring 2009 21


Global Memory2
 An example: To count how many time a
function is called.
 An alternative example: Two functions are
used to modify a global counter.

dr.dcd.h CS 101 Spring 2009 22


Global Memory3

dr.dcd.h CS 101 Spring 2009 23


Random Number Generator
 It is important to know that the real world does not
provide perfect measurements.
 So the ideal simulated data needs to add some
random noise.
 The simulated noise is usually created by a random
number generator.
 The build-in random number generator function
rand generates values in the range of [0.0, 1.0).
 Then the generated noise values can be scaled and
leveled.

dr.dcd.h CS 101 Spring 2009 24


Random Number Generator2
 The random numbers are in fact generated by a
deterministic function; i.e. the sequence of numbers
are fixed.
 The function returns a different and apparently
random number each time it is called. It is because
the function has started at a different starting point
internally each time it is called.
 The starting point is called a seed and it is set as a
global valable.

dr.dcd.h CS 101 Spring 2009 25


Random Number Generator3
 Example: two set of random numbers in the range
of [-0.5, 0.5].

dr.dcd.h CS 101 Spring 2009 26


Example 6.4: User Defined
Random Number Generator
 A simple random number generator can be
defined by the following equation:
n1 = a random seed
ni+1 = mod(8121*ni+28411, 134456)
rani = ni 134456
where 134456 is the total highest number in
the sequence and each new ni+1 is set as the
next seed.

dr.dcd.h CS 101 Spring 2009 27


Example 6.4: User Defined
Random Number Generator2

dr.dcd.h CS 101 Spring 2009 28


Example 6.4: User Defined
Random Number Generator3

dr.dcd.h CS 101 Spring 2009 29


Persistent Memory
 When a function finishes executing, the
workspace created for that function is
destroyed, so all local variables within that
workspace will disappear.
 The next time the same function is called, a
new workspace will be created.
 Sometimes, it is necessary to preserve local
variables between calls to a function.

dr.dcd.h CS 101 Spring 2009 30


Persistent Memory2
 Persistent memory is a special mechanism
to allow local variables to be preserved
between calls to a function.
 Syntax: persistent variable

dr.dcd.h CS 101 Spring 2009 31


Persistent Memory3
 To rewrite a previous example: To count how
many time a function is called.

dr.dcd.h CS 101 Spring 2009 32


Persistent Memory4
 How to reset the associated counter?

dr.dcd.h CS 101 Spring 2009 33


Homework Assignment #13
 6.9 Exercises
 Page 268: 6.6, 6.7, 6.14
 This homework is for your reference.

dr.dcd.h CS 101 Spring 2009 34


Chapter 7
Advanced Features of
User-Defined Functions

dr.dcd.h CS 101 /SJC 5th Edition 1


Function Functions
 Function function is a function whose input
arguments include the names or handles of
other functions.
 syntax: func(handler, range);
where func is a function function,
handler is the input function, and
range is the range of the handler.
 For example:
feval: evaluate a named function
fplot: plot a named function
fzero: find a zero of a named function

dr.dcd.h CS 101 /SJC 5th Edition 2


Function Functions2
 Three ways to define function handlers:
 Define handlers as strings, e.g.
cs= ’sin(x)-cos(3*x)’;
 Define handlers as inline functions, e.g.
fh = inline (’sin(x)-cos(3*x)’);
 Define handlers as anonymous functions, e.g.
an=@(x)(sin(x)-cos(3*x));

dr.dcd.h CS 101 /SJC 5th Edition 3


Function Functions3
 For example:

dr.dcd.h CS 101 /SJC 5th Edition 4


Function Functions4
 More example: to draw

dr.dcd.h CS 101 /SJC 5th Edition 5


Function Functions5
 To create a function function myplot.
 Calling syntax: myplot(handler, limits)
 handler is a function string,
 limits is the range of function in [min, max].
 The key is to convert the given function string to
a function handler so the build-in function feval
can be used.

dr.dcd.h CS 101 /SJC 5th Edition 6


Function Functions6
 To create a function function myplot.

dr.dcd.h CS 101 /SJC 5th Edition 7


Function Functions7

dr.dcd.h CS 101 /SJC 5th Edition 8


Subfunctions
 It is possible to place more than one function in a
single file.
 The topmost function is called primary function,
while the rest are called local functions or
subfunctions.
 All functions begin with their own function definition
line.
function primaryFunc(inarg_list)
primaryFunc statements
z=funcSub(x, y);
Return

function c=subFunc (a, b)


subFunc statements
return

dr.dcd.h CS 101 /SJC 5th Edition 9


Subfunctions2
 For example: Create a function mystats to compute
the mean and the median of a given array.
Functions mean and median are two local functions
of mystats.

dr.dcd.h CS 101 /SJC 5th Edition 10


Subfunctions3

dr.dcd.h CS 101 /SJC 5th Edition 11


Private Functions
 Private functions are functions that reside in
subdirectories with the special name private.
 A private function can be called in an M-file that
resides in the directory immediately above that
private subdirectory.
 For example, assume the directory cwd is the
current working directory and it has a sub-
directory called private. It can contain functions
that only the functions in cwd can call.

dr.dcd.h CS 101 /SJC 5th Edition 12


Nested Functions
 You can define functions within the body of any
function. These are said to be nested within the
outer function.
 A nested function has its own workspace. It also has
access to the workspaces of all functions in which it
is nested.
 For example, a variable that has a value assigned to
it by the primary function can be read or overwritten
by a function nested at any level within the primary.

dr.dcd.h CS 101 /SJC 5th Edition 13


Nested Functions2
 An illustration of a nested function:

dr.dcd.h CS 101 /SJC 5th Edition 14


Order of Function Evaluation
Order Descriptions
Checks to see if there is a nested function with the
1
specified name. If so, it is executed.
Checks to see if there is a subfunction with the
2
specified name. If so, it is executed.
Checks to see if there is a private function with the
3
specified name. If so, it is executed.
Checks to see if there is a function with the specified
4
name in the current directory. If so, it is executed.
Checks to see if there is a function with the specified
5 name on the MATLAB path. MATLAB will execute the
first file with the right name found on the path.

dr.dcd.h CS 101 /SJC 5th Edition 15


Recursive Functions
 Recursion is a devious construction which allows a
function to call itself.
 The function may call itself forever; so a terminating
statement is necessary.
 An individual workspace will be created each time a
function call itself. Therefore, it needs extra
memory space to accommodate the overhead of the
recursion.
 For example:
n! = n * (n-1)!
factorial(n)=n*factorial(n-1)

dr.dcd.h CS 101 /SJC 5th Edition 16


Recursive Functions2
 So, each loop can be rewritten as a recursive
function. For example:
n!=n*(n-1)!
It can be represented as:
factorial(n)=n*factorial(n-1)

% n-factorial use a loop % recursive n-factorial


res=1; function res=factorial(n)
for i=n:-1:2 if n<2
res=res*i; res=1;
end else
res=n*fatorial(n-1);
end

dr.dcd.h CS 101 /SJC 5th Edition 17


More Plotting Functions
 ezplot
 fplot

dr.dcd.h CS 101 /SJC 5th Edition 18


Homework Assignment #14
 7.9 Exercises
 Page 251: 7.4, 7.5, 7.12, 7.18
 This homework is for your reference.

dr.dcd.h CS 101 /SJC 5th Edition 19

You might also like