Vous êtes sur la page 1sur 65

A Hands on Introduction to MATLABr

Accompanying Manual, Second Edition

Presented by:
Dr. Thomas Chmielewski, Ph.D.
Donald J. Bucci
on

Saturday, May 31st, 2014


Saturday, June 7th, 2014

Hosted by: Sponsored by:


Department of Electrical and Computer Institute of Electrical and Electronics
Engineering Engineers (IEEE)
Drexel University Philadelphia Section
Revision History

Version Date Author(s) Description


2.1 Jun 21, 2014 DB Typo fixes. Added more detail on matrix selection.
2.0 May 29, 2014 DB, TC Second edition. See Forward.
1.0 Oct 2, 2010 DB, TC Initial document.

Copyright © 2014 by
Donald Bucci and Tom Chmielewski
All Rights Reserved

Page i
Page ii
Foreward

The IEEE Philadelphia Section Hands on Introduction to MATLABr is a two-day workshop meant
as an introduction to MATLABr and its toolboxes. During the first day, students are introduced
to the interface, syntax, and data structures used by MATLABr . During the second day, students
are introduced to a selection MATLABr toolboxes through hands-on demonstrations. By the end
of the course, students should be able to read through the MATLABr help documentation and
teach themselves how to use any of the toolboxes, given a knowledge of the corresponding technical
background.

MATLABr was developed by the MathWorksr Corporation as both a computer language and a
set of tools for designing and simulating systems in diverse areas such as Bioinformatics, Controls,
and Signal Processing. It also includes facilities for for performing embedded system design and
testing.

This workshop will introduce the participants to MATLABr computational and graphics capabil-
ities by means of hands on tutorials and exercises. In addition to elements of the language, we
will give examples of the use of cell mode for rapid code development and testing, and the use
of signal and image processing tools to model systems and observe their output (including FFT
with windowing, digital filtering design and reading data from Excel files). We will also introduce
the use of handle graphics to prepare graphical results and computer animations. A sequence of
projects will be available to guide the student through the important features of MATLABr , but
additional projects will be provided for those wishing to develop a different set of skills as well as
demonstrations of advanced functionality. Staff will include presenters and teaching assistants to
work closely with the participants and assist in troubleshooting MATLABr code.

The second edition of this manual covers the same content of the first edition, but in much
greater detail. The figures and commands have been updated to reflect the changes present up
to MATLABr r2012a. New concepts relevant to every day MATLABr use which were not covered
in the first edition are introduced. The handbook formatting has also been significantly updated.

About the authors:

Thomas Chmielewski is the owner of TAC Consulting Co. LLC, which specializes in the
modeling and simulation of control systems. He received his Ph.D. from Drexel University,
where he is also a teaching professor.

Donald J. Bucci is a Ph.D. student within the Electrical and Computer Engineering De-
partment of Drexel University, under the advisement of Moshe Kam. He has had over five
years experience in MATLABr programming, specifically in teaching MATLABr and develop-
ing MATLABr teaching resources.

Page iii
Page iv
Contents

1 Introduction to MATLABr 1
1.1 User Interface and Simple Commands . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Saving and Interacting with Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.1 Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.2 Arrays and Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.3 Matrix and Vectorized Operations . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Basic Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4 Builtin Help Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2 MATLAB Scripts and Functions 13


2.1 Scripting Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.1.1 The MATLABr Editor and a Basic Script . . . . . . . . . . . . . . . . . . . 13
2.1.2 Debugging Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.1.3 Organizing and Formatting Scripts: Cell Mode . . . . . . . . . . . . . . . . . 17
2.1.4 Publishing Cell Mode Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.2.1 Function Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.2.2 Multiple Functions in a single M-file (Subfunctions) . . . . . . . . . . . . . . 21
2.2.3 Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

3 Program Flow and Input/Output Control 23


3.1 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.2 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2.1 For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2.2 While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.2.3 Loop Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.3 Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.3.1 If-Else Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.3.2 Switch-Case Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.4 I/O Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.4.1 Command window I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.4.2 Excel Spreadsheet I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.5 Miscellaneous Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

Page v
4 Symbolic Math 33
4.1 Symbolic Variables and Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.1.1 Working with Symbolic Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.1.2 Algebraic Manipulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.1.3 Limits, Integration, and Differentiation . . . . . . . . . . . . . . . . . . . . . 34
4.2 Advanced Symbolic Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.2.1 Functional Inverses and Compositions . . . . . . . . . . . . . . . . . . . . . . 36
4.2.2 Solving Systems of Polynomial Equations . . . . . . . . . . . . . . . . . . . . 36
4.2.3 Solving Systems Differential Equations . . . . . . . . . . . . . . . . . . . . . . 37
4.2.4 Transforms of Symbolic Equations . . . . . . . . . . . . . . . . . . . . . . . . 38
4.3 Plotting with Symbolic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.4 Generating Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

5 Selected Topics and Examples 41


5.1 Linear Regression and Curve Fitting . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5.2 Numerically Solving Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . 41
5.2.1 ODE45 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
5.2.2 Solving Piecewise Differential Equations . . . . . . . . . . . . . . . . . . . . . 43
5.2.3 Solving Systems of Differential Equations . . . . . . . . . . . . . . . . . . . . 45
5.3 Frequency Domain Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

6 Additional MATLABr Toolboxes and Resources 49

Page vi
List of Tables

1.1 Common MATLABr commands, analogous to calculator commands. . . . . . . . . . 2

1.2 Predefined MATLABr variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.3 Matrix generation commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.4 Matrix data selection notation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.5 Matrix and vectorized operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

1.6 Plot and plot formatting commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2.1 Script debugging buttons, located at the top of the editor window. . . . . . . . . . . 16

3.1 Common relational operators used in MATLABr . . . . . . . . . . . . . . . . . . . . 24

Page vii
Page viii
List of Figures

1.1 General MATLABr user interface and window layout. . . . . . . . . . . . . . . . . . 2

1.2 Resulting figure of Example 1.7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

1.3 Resulting figure of Example 1.8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

1.4 Resulting figure of Example 1.9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

1.5 Output generated when calling help plot from the command window. . . . . . . . 11

1.6 Output generated when calling doc plot from the command window. . . . . . . . . 11

2.1 MATLABr editor interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

2.2 M-file name with asterisk, denoted unsaved work. . . . . . . . . . . . . . . . . . . . . 14

2.3 Current folder warning after executing a script which is not on the MATLABr path. 15

2.4 Illustration of breakpoints for controlling program flow when debugging a script. . . 16

2.5 An example of an error message in the command window. . . . . . . . . . . . . . . . 17

2.6 The published HTML document using the cell mode script with markup, given in
Example 2.3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2.7 Plot window after running Example 2.6. . . . . . . . . . . . . . . . . . . . . . . . . . 22

3.1 Plot window after running the first cell of Example 3.2. . . . . . . . . . . . . . . . . 26

3.2 Plot windows after running Example 3.7. . . . . . . . . . . . . . . . . . . . . . . . . 31

5.1 Curve fitting results after running Example 5.1. . . . . . . . . . . . . . . . . . . . . . 42

5.2 Numerical solution of Example 5.2 using ode45. . . . . . . . . . . . . . . . . . . . . 44

5.3 Numerical solution of Example 5.3 (piecewise differential equation) using ode45. . . 45

Page ix
5.4 Numerical solution of Example 5.5 (Lorentz attractor) using ode45. . . . . . . . . . 46

5.5 Time and frequency domain representation of the signal created in Example 5.7. . . 47

6.1 Example commands in the MuPAD interface. . . . . . . . . . . . . . . . . . . . . . . 50

Page x
List of Examples

1.1 A selection of commands which can be entered into the command window. . . . . . . 3

1.2 Assignment statements, unsuppressed output. . . . . . . . . . . . . . . . . . . . . . . 3

1.3 Assignment statements with the output suppressed using semicolons. . . . . . . . . . 4

1.4 An example of concatenating matrices. . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.5 Row replacement for solving a linear system. . . . . . . . . . . . . . . . . . . . . . . 6

1.6 Example of selected matrix operations. . . . . . . . . . . . . . . . . . . . . . . . . . . 7

1.7 Basic plotting of coordinate pairs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

1.8 Modified Example 1.7 with plot formatting. . . . . . . . . . . . . . . . . . . . . . . . 9

1.9 Plotting multiple equations of lines, with additional short hand notation. . . . . . . 10

2.1 Example 1.9 with formatting and comments added. . . . . . . . . . . . . . . . . . . . 14

2.2 Example 1.9 as a cell mode script. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

2.3 Example 1.9 as a cell mode script with markup. . . . . . . . . . . . . . . . . . . . . . 19

2.4 An example of a MATLABr function (ex2 4.m). . . . . . . . . . . . . . . . . . . . . 20

2.5 Example 2.4 written using subfunctions (ex2 5.m). . . . . . . . . . . . . . . . . . . . 21

2.6 Example of an anonymous function, used to calculate sinc(x). . . . . . . . . . . . . . 22

3.1 Relational operator usage examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

3.2 For loop examples in plotting and in calculations. . . . . . . . . . . . . . . . . . . . . 25

3.3 While loop example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

3.4 If-else statement example implementation. . . . . . . . . . . . . . . . . . . . . . . . . 27

Page xi
3.5 Switch-case statement example implementation. . . . . . . . . . . . . . . . . . . . . . 28

3.6 Example of command window I/O with input and fprintf. . . . . . . . . . . . . . 29

3.7 Implementation of xlsread. Requires the spreadsheet ex3 7.xlsx. . . . . . . . . . . 30

3.8 Implementation of xlswrite. Produces the spreadsheet ex3 8.xlsx. . . . . . . . . . 31

4.1 Creating symbolic objects with sym and syms. . . . . . . . . . . . . . . . . . . . . . 34

4.2 Algebraic manipulation and simplification of symbolic expressions. . . . . . . . . . . 35

4.3 Examples of using the symbolic toolbox to perform linear algebra manipulations. . . 35

4.4 Examples of using the symbolic toolbox to assist in calculus analyses. . . . . . . . . 36

4.5 Functional composition and inverse with the symbolic toolbox. . . . . . . . . . . . . 37

4.6 Solving systems of polynomial equations with the symbolic toolbox. . . . . . . . . . 37

4.7 Solving systems of differential equations with the symbolic toolbox. . . . . . . . . . . 38

4.8 Laplace and Fourier transforms with the symbolic toolbox. . . . . . . . . . . . . . . 39

4.9 Creating 2D and 3D plots from symbolic objects. . . . . . . . . . . . . . . . . . . . . 40

4.10 Creating anonymous functions from symbolic expressions. . . . . . . . . . . . . . . . 40

5.1 Using polyfit and polyval for curve fitting. . . . . . . . . . . . . . . . . . . . . . . 42

5.2 Example using ODE45 with an anonymous function. . . . . . . . . . . . . . . . . . . . 43

5.3 Example using ODE45 to solve a piecewise differential equation. . . . . . . . . . . . . 44

5.4 M-file function of the differential equation used in Example 5.3. . . . . . . . . . . . . 44

5.5 Example using ODE45 to solve a system of differential equations. . . . . . . . . . . . 46

5.6 M-file function of the differential equation used in Example 5.5. . . . . . . . . . . . . 46

5.7 An example of frequency analysis in MATLABr with fft. . . . . . . . . . . . . . . 47

Page xii
Chapter 1

Introduction to MATLABr

As previously mentioned, MATLABr consists of both a programming language and interface to help
assist in data analysis, algorithm development, and visualization. At its core, MATLABr operates
in a manner similar to a calculator. In this chapter, we explain the MATLABr user interface
and some simple commands and operations. We then discuss how variables are handled in the
MATLABr memory for numerics, strings, and matrices. Using arrays, we introduce the notion of
generating and formatting simple 2D plots. Finally, we conclude this chapter with an introduction
to the MATLABr help documentation.

1.1 User Interface and Simple Commands

Launch MATLABr , and a window layout similar to Figure 1.1 should appear. The default MAT-
LAB window should have three sections, with an optional fourth section.

1. Command Window: This is where MATLAB commands are entered for immediate execu-
tion. To execute a command, type it at the command prompt (>>) and press the enter key.
The command window also displays errors resulting from incorrect usage of MATLABr com-
mands or syntax.

2. Command History: A log of all commands entered into the command window appear here,
sorted by the dates and times MATLABr was initialized. You can re-execute any previous
command by simply double clicking on its line in the command history. You can also cycle
through the command history by using the up and down arrow keys in the command window.

3. Worskpace: Similar to a calculator, MATLABr has the ability to save and recall values from
variables. The workspace is a list of the names and values of each variable currently stored in
the MATLABr memory. The workspace is automatically cleared after MATLABr is closed.

4. Current Folder (optional): This fourth section displays the contents of the working direc-
tory currently in use by MATLABr .

Page 1
CHAPTER 1. INTRODUCTION TO MATLABr

Figure 1.1: General MATLABr user interface and window layout.

Table 1.1 shows a list of common commands that can be entered into the command window. These
commands are similar to one which would be entered into a calculator.

Table 1.1: Common MATLABr commands, analogous to calculator commands.

Commands Description Examples


+,-,*,/ Addition, subtraction, multiplication, and di- 2*3, 5+7
vision.
ˆ Exponentiation. 3ˆ2
() Parentheses. Tells MATLABr to execute the 3ˆ(4+5)
commands within the parentheses before nor-
mal order-of-operations.
exp(x) Find the result of the exponential function ex , exp(3*2)
where e is Euler’s number.
sin(x), cos(x) Trigonometric functions. Takes sine or cosine cos(0), tan(3.141/4)
of x, where x is in radians.
clear Clear all variables from the workspace
clc Clear the contents of the command window

There are also a few pre-defined variables that exist by default in the MATLABr memory. These
are summarized in Table 1.2, and can be used interchangeably with the values that they represent
in various MATLABr commands.

Page 2
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

Table 1.2: Predefined MATLABr variables.

Variable Description
pi Standard value of pi (3.14159 . . .)

i, j Imaginary numbers ( −1)
inf Infinity. Evaluated as a divide by zero.
NaN Not a Number. Returned by 0/0 and inf/inf.

Example 1.1 shows a few lines of MATLABr commands that can be typed into the command
window. Try typing in some of the commands, and observe the outputs generated in the command
window.

Example 1.1: A selection of commands which can be entered into the command window.
2*pi
pi*j + 3
38*sin(pi/4) + cos(pi)
sin(pi)ˆ2 + cos(pi)ˆ2

1.2 Saving and Interacting with Variables

Notice in Example 1.1 that the results of each command generates a variable in the workspace.
More specifically, every MATLABr command which produces some kind of output saves it by
default in a variable called “ans”. The creation of any variable in MATLABr is known as an
assignment statement.

1.2.1 Assignment Statements

An assignment in MATLABr is denoted through the use of an equal sign (=). Example 1.2 shows
an example on how to create and use a variable. The right hand side of the equal sign contains
the math operations to be evaluated. The left hand side of the equal sign defines the name of the
variable.

Example 1.2: Assignment statements, unsuppressed output.


x=2
y=3
output=x+3*y

Notice that when the commands of Example 1.2 are entered into the command window, there
is a response associated with the commands x=2 and y=3. In some cases, this information may
be useful. For trivial assignment statements like these however, it may be useful to suppress the
output from the command window. This is accomplished by use of a semicolon (;) at the end of
each assignment statement whose output we would like to suppress (e.g., Example 1.3).

Page 3
CHAPTER 1. INTRODUCTION TO MATLABr

Example 1.3: Assignment statements with the output suppressed using semicolons.
x=2;
y=3;
output=x+3*y

Be aware of the following when creating variables:

ˆ Variables names must start with a letter, and they are case sensitive. Variables can only
contain upper/lower case letters, numbers, and underscores.

ˆ Once created, variable names will appear in the workspace (Figure 1.1). The contents of any
variable can be viewed by double-clicking its name in the workspace.

ˆ The predefined variable names of Table 1.2 can be overwritten with assignment statements.
To reset these variables back to their original state, use the clear command, followed by the
name of the variable (e.g., clear pi or clear i).

1.2.2 Arrays and Matrices

In addition to variables containing scalars, variables can also be constructed as arrays or matrices.
A matrix of elements in MATLABr is defined through the use of square brackets ([]). Spaces (or
commas) are used to delineate elements in a row, whereas semicolons are used to break between
rows. For example, the command [1 2 3; 4 5 6] creates the matrix
 
1 2 3
(1.1)
4 5 6

Any data types in MATLABr can be concatenated into an array or matrix, including other arrays
or matrices. Example 1.4 shows an example of concatenating submatrices into a larger matrix.

Example 1.4: An example of concatenating matrices.


A11 = [1 2; 3 4];
A12 = zeros(2,2);
A21 = ones(2,2);
A22 = A11.';

A = [A11 A12; A21 A22]

If entered correctly, the commands shown in Example 1.4 create the following matrix (dotted lines
added for convenience).  
1 2 0 0
 3 4 0 0 

 1 1 1 3 
 (1.2)
1 1 2 4

Notice that we have introduce a few extra commands in Example 1.4. These commands are sum-
marized in Table 1.3, along some other frequently used matrix generation commands.

Page 4
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

Table 1.3: Matrix generation commands.

Command Description Examples


zeros(M,N) Create a matrix of zeros with M rows and N zeros(2,3), zeros(2)
columns. If N is unspecified, then the gener-
ated matrix is square.
ones(M,N) Create a matrix of ones with M rows and N ones(1,4), ones(3)
columns. If N is unspecified, then the gener-
ated matrix is square.
' Take the Hermitian of a matrix (complex con- A'
jugate transpose).
.' Take the transpose of a matrix. A.'

Finally, we can replace or extract elements from within a matrix already in memory. Table 1.4 shows
a few different ways to select elements from a matrix. When these notations are on the right-hand-
side of an assignment statement (or by themselves), they extract elements from a matrix. When
they are on the left-hand-side of an assignment statement, they replace elements in a matrix.

Table 1.4: Matrix data selection notation.

Notation Description Examples


A(k) Delineates the k th element from matrix A, counted myMatrix(4)
down the rows of the matrix. For example, in a 3x3
matrix A(4) would return the value in the first row
and second column.
A(m,n) Delineates an element from the matrix A in the mth myMatrix(1,2)
row and nth column.
A(m,:) Delineates the elements from the matrix A in the mth myMatrix(1,:)
row (and all columns). Note that m can be an array myMatrix([2 3],:)
of values, delineating multiple rows.
A(:,n) Delineates the elements from the matrix A in the nth myMatrix(:,5)
column (and all rows). Note that n can be an array myMatrix(:,[5 2])
of values, delineating multiple columns.

Example 1.5 illustrates some of these matrix extraction and replacement techniques to find the
solution of the following system of linear equations

x1 + 2x2 + 3x3 = 9
2x1 − x2 + x3 = 8 (1.3)
3x1 − x3 = 3

Page 5
CHAPTER 1. INTRODUCTION TO MATLABr

by converting the augmented matrix


 
1 2 3 9
 2 −1 1 8  (1.4)
3 0 −1 3

to the form
 
1 0 0 #
 0 1 0 # . (1.5)
0 0 1 #

This conversion can be done completely with the notations given in Table 1.4. We first define the
augmented matrix as a variable in MATLABr . Then we copy over the matrix into a temporary
variable which we will perform the operations on. Each row replacement operation is then carried
out by selecting data from different rows of the matrix, adding them together, and then overwriting
corresponding rows of the matrix. Remember, you can remove the semicolon from any of
the lines in Example 1.5 to observe what each replacement command does to the
temporary variable!

Example 1.5: Row replacement for solving a linear system.


myMatrix = [1 2 3 9; 2 -1 1 8; 3 0 -1 3]
A = myMatrix;

A(2,:) = -2*A(1,:) + A(2,:);


A(3,:) = -3*A(1,:) + A(3,:);
A(2,:) = A(2,:)/-5;
A(3,:) = 6*A(2,:) + A(3,:);
A(3,:) = A(3,:)/-4;
A(2,:) = -1*A(3,:) + A(2,:);
A(1,:) = -3*A(3,:) + A(1,:);
A(1,:) = -2*A(2,:) + A(1,:)

The command rref(A) will also produce the required form from the augmented matrix A. You
may want to use rref to verify that the row operations were complted successfully.

1.2.3 Matrix and Vectorized Operations

For matrices, MATLABr defines addition, subtraction, multiplication, division, and exponentia-
tion in terms of their linear algebra definitions. For users not familiar with linear algebra, these
overloaded commands usually lead to problems. For example, users almost always write A*B to
attempt to multiply every element in matrix A with every corresponding element in matrix B. In
this case however, MATLABr will attempt to perform the matrix multiplication of A and B. In
order to obtain the intended result, the multiplication operation must be vectorized. This is done by
preceding the operation with a period, that is, A.*B. Table 1.5 shows a listing of matrix operations
and their vectorized counterparts. A few sample commands from Table 1.5 are demonstrated in
Example 1.6.

Page 6
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

Table 1.5: Matrix and vectorized operations.

Notation Description
A+B, A-B Add or subtract matrices A and B. A and B must have the same
size dimensions. If B is scalar, then the operation is the scalar added or
subtracted to every value in the matrix A.
A*B Matrix multiply A and B. There must be as many columns in A as
there are rows in B.
A.*B Multiply the elements in A with every corresponding element in B.
A/B Matrix multiply A and B −1 .
A./B Divide the elements in A with every corresponding element in B. A and B
must have the same size dimensions.
Aˆk Matrix multiply A with itself k times. A must be a square matrix.
A.ˆk Raise each element in A to the k th power.

Example 1.6: Example of selected matrix operations.


A = [1 2 3; 4 5 6; 7 8 9];
B = [1 3 5; 2 1 -1; 0 1 0];

AplusB = A + B

Aplus2 = A + 2

AmatrixMultB = A*B

AtimesB = A.*B

sqrtB = B.ˆ(1/2)

1.3 Basic Plotting

Some of the most powerful aspects of MATLABr lie in its data visualization capabilities. The
most basic of these aspects is forming a 2D plot in a figure window. Given two arrays of values, X
and Y, the command plot(X,Y) plots a line with the coordinate pairs whose x-components are in
the array X and y-components are in the array Y.

For instance, suppose we wanted to plot the line defined by the coordinate pairs (0, 0), (0, 2), (2, 2),
(2, 0), and (4, 0). This is accomplished by placing the x-components of the coordinate pairs in an
array, and the y-components in the corresponding locations of another array. These commands are
summarized in Example 1.7.

Example 1.7: Basic plotting of coordinate pairs.


xComponents = [0 0 2 2 4];
yComponents = [0 2 2 0 0];

plot(xComponents, yComponents)

Page 7
CHAPTER 1. INTRODUCTION TO MATLABr

Figure 1.2: Resulting figure of Example 1.7.

After calling the plot command, the figure of Figure 1.2 appears. Notice that in this case, some of
the lines are hard to see because they are hidden behind the figure axes. To make the lines easier to
see, we can format the plot window by modifying linespec properties of the drawn line. There are
many ways to do this, however a simple solution is to specify a linespec string as the third input
of the plot command. Example 1.8 shows a modification of Example 1.7 that specifies a sample
linespec string, along with some additional formatting of the plot window. The updated plot is
shown in Figure 1.3. A description of the additional commands used can be found in Table 1.6.

Table 1.6: Plot and plot formatting commands.

Notation Description
plot() Command used to plot coordinate pairs and connect them using line
segments. Also can be used to set linespec properties such as data
symbols, line style, and line color.
xlim() or ylim() Command used to set the limits on either the x-axis or y-axis. The
limits are defined using a 2 element array, where the first element
specifies the minimum limit and the second element specifies the
maximum.
xlabel() or ylabel() Command used to specify a text label for the x-axis or y-axis. The
input is a string, surrounded by single quotes.
title() Set the title for the plot, which appears at the top of the figure
window. The input is a string, surrounded by single quotes.
legend() Add a legend to the current plot. The inputs are multiple strings,
representing the label for each line on the plot.
grid on Turns on the grid lines for the currently selected figure window.
close all Close all currently open figure windows

Page 8
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

Example 1.8: Modified Example 1.7 with plot formatting.


xComponents = [0 0 2 2 4];
yComponents = [0 2 2 0 0];

plot(xComponents, yComponents,'ro-')

xlabel('X Components')
ylabel('Y Components')
grid on

xlim([-.5 4.5])
ylim([-.5 2.5])

title('A sample plot')

Figure 1.3: Resulting figure of Example 1.8.

We conclude the introduction on plotting by describing how one can plot equations of a lines using
the vectorized matrix operations from Table 1.5. For instance, suppose we wanted to plot two
functions on the same figure window, defined by
sin(x2 )
y1 = (1.6)
x
y2 = sin x2 (1.7)

and for values of x between −π and π. Example 1.9 presents the commands to do this. Notice that
we have introduce a few extra notations.

ˆ To create the variable xValues, we use the colon operator. In Example 1.9, it is used to
generate an array of values that go from −π to π in increments of 0.1.
ˆ There are many ways to plot more than one line in the same figure window. In Example 1.9,
we do this by just concatenating more coordinate pairs and linespec strings onto the end of
a single plot command. This syntax is special for the plot command, and can be extended as
many times as desired.

Page 9
CHAPTER 1. INTRODUCTION TO MATLABr

Figure 1.4: Resulting figure of Example 1.9.

ˆ The legend command uses two strings: 'y 1' and 'y 2'. These are typset by the legend box
using LaTeX, and as a result the numbers 1 and 2 appear as subscripts.

Example 1.9: Plotting multiple equations of lines, with additional short hand notation.
xValues = -pi:0.1:pi;
y1 = sin(xValues.ˆ2)./xValues;
y2 = sin(xValues.ˆ2);

plot(xValues,y1,'r-',xValues,y2,'b--')

grid off
xlabel('Radians')
ylabel('Functional Values')
legend('y 1','y 2')

xlim([-pi pi])
ylim([-1.2 1.2])

The resulting figure from execution of Example 1.9 is shown in Figure 1.4.

1.4 Builtin Help Documentation

One convenient aspect of MATLABr is its help functionality. For any command in MATLABr ,
typing help followed by the command in the command window produces a short writeup that
shows a brief overview of what the command does, along with some of the commonly used syntax.
For example, typing help plot in the command window yields output similar to that shown in
Figure 1.5. For plot, this is a good way to determine how the linespec string is formed when
formatting each line in a plot window. Alternatively, the command doc plot opens up the cor-
responding help page in the MATLABr documentation (Figure 1.6). The help page contains the

Page 10
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

Figure 1.5: Output generated when calling help plot from the command window.

Figure 1.6: Output generated when calling doc plot from the command window.

information shown by the help command, in addition to some additional resources and examples.

Page 11
Page 12
Chapter 2

MATLAB Scripts and Functions

Although the command window is convenient for quick calculations, it becomes very difficult to
work with when performing more complex analyses. A script in MATLABr is defined as an
external file (i.e., an M-file) that contains a sequence of MATLABr statements. They are useful
for automating blocks of MATLABr commands, such as computations which must be performed
repeatedly. Functions in MATLABr are analogous to commands and can be used to greatly
simplify frequently used segments of a script.

We begin this section by overviewing the MATLABr editor for writing scripts. We then address how
script debugging works, and how to organize scripts in cell mode for publishing MATLABr scripts
to PDF or HTML files. We conclude by describing various implementations techniques for creating
custom MATLABr functions.

2.1 Scripting Fundamentals

In MATLABr , scripts are denoted as M-files. Each M-file contains a list of commands and com-
ments to help describe the script writer’s intentions. Scripts can be formatted in such a way to
automate publishing the commands contained in them, along with their results.

2.1.1 The MATLABr Editor and a Basic Script

To create a new script, you can click the button at the top of the MATLABr window, or navigate
to File → New → Script. A new window called the editor appears, similar to Figure 2.1. This
window works like a cross between the command window and a notepad. Commands can be entered
just as they would be into the command window, and then executed in succession. In addition to
normal commands, scripts can also contain comments. A comment in a script is any text that is
preceded by a %. Comments are used to describe the script author’s intent in how the different lines
of the M-file are organized and written. Consider Example 1.9 from the last chapter. Example 2.1
contains the same code as Example 1.9, but the formatting is altered to include comments. Copy
the contents of Example 2.1 into a new script file, and save it as ex2 1.m.

Page 13
CHAPTER 2. MATLAB SCRIPTS AND FUNCTIONS

Figure 2.1: MATLABr editor interface.

Example 2.1: Example 1.9 with formatting and comments added.


% PLOTTING SOME FUNCTIONS
% This is an example script file with some comments. It uses the same
% content from Example 1.9 in the text.

% This first command generates values from -pi to pi in increments of 0.1


xValues = -pi:0.1:pi;

% We then evaluate the two functions using vectorized notation.


y1 = sin(xValues.ˆ2)./xValues;
y2 = sin(xValues.ˆ2);

% This plots the independent and dependent variables of the two functions,
% along with handling the formatting of each line
plot(xValues,y1,'r-',xValues,y2,'b--')

% Here we format the plot window


grid off
xlabel('Radians')
ylabel('Functional Values')
legend('y 1','y 2')

% Finally, the x and y axis limits are set.


xlim([-pi pi])
ylim([-1.2 1.2])

Figure 2.2: M-file name with asterisk, denoted unsaved work.

Notice that as changes are being made in the script file, the top of the editor appears similar to
Figure 2.2. Namely, the filename of the script is appended with an asterisk. In this manner,
an asterisk denotes that there is unsaved work in the script that is currently active in the editor.
Before executing scripts it is VERY IMPORTANT to save your work! If you do not save
your work before running a script, your changes might not propagate through correctly.

Page 14
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

Figure 2.3: Current folder warning after executing a script which is not on the MATLABr path.

To run the script file, press F5, or click the button. Depending on where you saved the script, a
window similar to Figure 2.3 may appear. To run any script in MATLABr , it must be located on
the MATLABr path. The MATLABr path is a list of directories which tells MATLABr where
to look for the M-files that define all of the possible commands which can be used. The current
working directory1 (or working directory) is a location that is always on the MATLABr path.
Therefore, the window popup of Figure 2.3 is there to remind you to set your working folder to the
location of the file you are trying to run; otherwise, MATLABr will be unable to run that script.
In general, you can just click the “Change Folder” button.

The following guidelines should ALWAYS be used when naming scripts.

ˆ NEVER use spaces or symbols (other than underscores) the following in m-file names.

ˆ NEVER start m-file names with numbers.

ˆ NEVER name m-files as commands, such as plot, sin, clear, title, etc.

If these guidelines are not adhered to then there is a good chance that your code might not work
as you would expect it to, if not at all!

2.1.2 Debugging Scripts

The editor window also makes debugging MATLABr scripts straightforward. Figure 2.4a shows
the side of the editor window where the line numbers are located. Notice that next to each line
with a MATLABr command, there is a hyphen. Clicking on any of the hyphen turns it into a
breakpoint, as denoted by a red dot (e.g., at line 14 in Figure 2.4b). If the script is run when
breakpoints are present, MATLABr is run in debug mode and will temporarily pause execution
of the code at each breakpoint until told to resume. The code will be run up until the breakpoint
(i.e., the command at the line of the breakpoint will not be executed).

When in debug mode, MATLABr gives program flow control by via the debug buttons located at
the top of the editor window. These buttons are shown and described in Table 2.1. In addition
to the buttons, the cursor in the command window changes from >> to K>> to indicate that
MATLABr is currently in debug mode. While in debug mode, the values of any variable in
memory from the script appear in the workspace. In addition, one can determine the value of a
variable in the workspace by holding the mouse over that variable’s name in the editor window.
1
If the script is in the current working directory, you can also run it by typing its name into the command window.

Page 15
CHAPTER 2. MATLAB SCRIPTS AND FUNCTIONS

(a) (b) (c)

Figure 2.4: Illustration of breakpoints for controlling program flow when debugging a script. (a) No
breakpoints. (b) Breakpoint at line 14. (c) Program flow halted by breakpoint at line 14. Line 14
has not yet been executed.

Table 2.1: Script debugging buttons, located at the top of the editor window.

Button Description
Set a break point in the script, based on what line the text
insert cursor is currently located at.
Clear a break point in the script, based on what line the text
insert cursor is currently located at or the breakpoint stop
cursor (green arrow, Figure 2.4c.
Execute the command at the break point stop cursor and
advance to the next command.
Step into the corresponding m-file for the function or com-
mand specified by the breakpoint stop cursor.
After stepping into a function or command, finish execution
of it and return to the calling function or script.
Execute the command at the break point stop cursor and
advance to the next breakpoint.
Exit debug mode.

The script will also stop prematurely if an error occurs. In MATLABr , errors occur from improper
syntax or an improper use of a command. If an error occurs, MATLABr will produce a “chime”
sound and red text will appear in the command window. Figure 2.5 shows an example of such an
error. The error will always give a brief description of the event, the name of the M-file it occurred
in, the location in the file where it occurred (i.e., line number), and the command that caused the
error. In the specific case of Figure 2.5, MATLABr is stating that it doesn’t recognize the function
name xlable having string inputs. This occurs at line 40 of ex2 3.m. An error like this one2 is
usually indicative of a misspelled MATLABr command.
2
For more error descriptions, see http://en.wikibooks.org/wiki/MATLAB_Programming/Error_Messages

Page 16
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

Figure 2.5: An example of an error message in the command window.

2.1.3 Organizing and Formatting Scripts: Cell Mode

A very convenient way of formatting MATLAB scripts is through the use of cell mode. Cell
mode presents a way of breaking up an M-file into discrete segments called cells. which assist in
organization of a script. Example 2.2 shows again the code from Example 1.9, however with cell
mode formatting applied. A cell delineator consists of two percent symbols followed by a space
(%%). A title can be given to a cell by specifying text next to a cell delineator. Furthermore, cells
can be given descriptions by placing comments on the lines immediately following the cell title
using a single percent sign followed by a space (%). Any other comments can be used as normal.

Example 2.2: Example 1.9 as a cell mode script.


%% Example 2.2 - Using Cell Mode

%% Overview of Example
% This is an example script file with some comments. It uses the same
% content from Example 1.9 in the text.

%% Generating the Data to Plot


% This first command generates values from -pi to pi in increments of 0.1
xValues = -pi:0.1:pi;

%%
% We then evaluate the two functions using vectorized notation.
y1 = sin(xValues.ˆ2)./xValues;
y2 = sin(xValues.ˆ2);

%% Plotting and Formatting


% This plots the independent and dependent variables of the two functions,
% along with handling the formatting of each line
plot(xValues,y1,'r-',xValues,y2,'b--')

%%
% Here we format the plot window
grid off
xlabel('Radians')
ylabel('Functional Values')
legend('y 1','y 2')

%%
% Finally, the x and y axis limits are set.
xlim([-pi pi])
ylim([-1.2 1.2])

Once the script has been placed in cell mode, light gray lines will appear between each cell of the
script. The active cell is the cell in which the text insert cursor is currently located in, and is

Page 17
CHAPTER 2. MATLAB SCRIPTS AND FUNCTIONS

highlighted yellow. To run the code in the current cell without saving and running the script, click
the button (CTRL+Enter). To evaluate the commands in the current cell and make the next cell
the current cell, click the button (CTRL+Shift+Enter). Executing the code within individual
cells in this manner allows for the debugging of subsets of a script without running the entire script.

2.1.4 Publishing Cell Mode Scripts

Finally, cell mode scripts can be published in a variety of different formats. The default format is an
HTML page3 . Each cell of the script is listed as a section in the page, with a table of contents at the
beginning. When published, MATLABr evaluates the script and shows every unsuppressed output,
along with every graph generated in the final published document. In addition, it is possible to
add many kinds of markup to the final published document, including images, different font styles,
bulleted/numbered lists, and LaTeX typeset math equations. A full list of these markups can be
found under Cell → Insert text markup.

Example 2.3 shows a final cell mode script example which is based on Example 1.9, but also includes
some text markup. A selection of the published output is shown in Figure 2.6. When including
images in the markup, MATLABr looks for them in a folder called “html”, which is created in
the MATLABr current directory after a script is published. The example of Example 1.9 defined
a relative path so that the image can just be placed in the current directory.

2.2 Functions

A function in MATLABr is nothing more than a set of commands (similar to a script file) with
defined inputs and outputs. Almost all of the inbuilt MATLABr functions such as plot, sin, and
exp all relate back to M-files in the base installation of MATLABr . MATLABr allows for the
creation of customizable functions in a manner that is similar to other programming languages.

2.2.1 Function Syntax

We first describe how a MATLABr function is constructed by use of an example. Example 2.4
is shows the syntax for a MATLABr function that takes in two coordinate pairs (given as two
element arrays) and computes the slope and y intercept of the linear line which connects them.
Notice that the function is saved in a file named ex2 4.m. In addition to the comments given in
the example, make note of the following.

ˆ A function is defined in this example by creating a new M-file, and writing the word function
on the first line of the file. The word function is followed by variable names which will be
passed from as the function outputs (enclosed in square brackets), an equal sign, the name of
the function, and finally comma-separated variable names which represent the different inputs
passed into the function (enclosed in parentheses). This first line is known as the function
3
For information on other formats, see http://www.mathworks.com/help/matlab/matlab_prog/
specifying-output-preferences-for-publishing.html

Page 18
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

Example 2.3: Example 1.9 as a cell mode script with markup.


%% Example 2.2 - Using Cell Mode

%% Overview of Example
% This is an example script file with some comments. It uses the same
% content from Example 1.9 in the text.

%% Including Markup for Published


% When publishing cell mode scripts, it's possible to include markup such
% as images, different font styles, bulleted lists, and even LaTeX typeset
% math. Here is an example of including the MathWorks logo. Notice that it
% must be in the same directory as this example file to work.
%
% <<../mathworkslogo.jpg>>
%

%% Generating the Data to Plot


% This first command generates values from -pi to pi in increments of 0.1
xValues = -pi:0.1:pi;

%%
% We then evaluate the two functions using vectorized notation. These
% functions are (using LaTeX markup to typset them),
%
% $$y 1 = \frac{\sin(xˆ2)}{x}$$
%
% $$y 1 = \sin(xˆ2)$$
y1 = sin(xValues.ˆ2)./xValues;
y2 = sin(xValues.ˆ2);

%% Plotting and Formatting


% This plots the independent and dependent variables of the two functions,
% along with handling the formatting of each line
plot(xValues,y1,'r-',xValues,y2,'b--')

%%
% Here we format the plot window
grid off, xlabel('Radians'), ylabel('Functional Values')
legend('y 1','y 2'), xlim([-pi pi]), ylim([-1.2 1.2])

template. In the case of Example 2.4, this function supports two outputs, three inputs, and
is named ex2 4.

ˆ The function name specified in the first line of the function must be the same as the
filename of the function (excluding the .m extension).

ˆ When running a function, it must be located in the MATLABr path (e.g., in the current
directory). Otherwise, MATLABr will return an error saying that the function is not defined.

ˆ MATLABr functions are usually not written in cell mode, as the benefits of writing code in
cell mode apply mainly to scripts.

Try running the function in Example 2.4 with a few of the following sample inputs. Take note of
how data is passed into the function and returned from it.

Page 19
CHAPTER 2. MATLAB SCRIPTS AND FUNCTIONS

Figure 2.6: The published HTML document using the cell mode script with markup, given in
Example 2.3.

Example 2.4: An example of a MATLABr function (ex2 4.m).


function [slope,Yintercept] = ex2 4(point1,point2)
% EX2 4 FUNCTION - Example of a MATLAB Function
% This function is an example, meant to showcase how a function is formed
% in MATLAB and some of the variables associated with function calls.
% This description here defined the "help text" for your function. If
% this function is in the current directory, try typing "help ex2 4"
% (without the quotes) and see what happens.
%
% This function will take two coordinates (point1 => (x1,y1)...point2 =>
% (x2,y2) and compute the slope of the line which connects the two points
% (slope) and where that line intercepts the y axis (Yintercept).

% First, compute the slope


xValues = [point1(1) point2(1)]; % X coordinates of each point
yValues = [point1(2) point2(2)]; % Y coordinates of each point
slope = (yValues(2) - yValues(1))/(xValues(2) - xValues(1));

% Then, compute the y intercept


Yintercept = yValues(1) - slope*xValues(1);

Page 20
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

ˆ ex2 4([1 1],[2 2])

ˆ slope = ex2 4([1 1],[2 5])

ˆ [m b] = ex2 4([1 1],[2 5])

2.2.2 Multiple Functions in a single M-file (Subfunctions)

Suppose we were working on a complicated function and wanted to break up its operation into dif-
ferent subfunctions. This is possible in MATLABr by specifying more than one function template
after the main function template. Example 2.5 shows Example 2.4 implemented using subfunctions.
In this setup, the body of the main and subfunctions must be ended using the end keyword. Notice
that the subfunctions can only be called from the scope of the main function (i.e., the first function,
corresponding to the name of the M-file).

Example 2.5: Example 2.4 written using subfunctions (ex2 5.m).


function [m,b]=ex2 5(pt1,pt2)
% EX2 5 FUNCTION - MATLAB Subfunction Examples
% This function is an example of breaking up operations into different
% subfunctions. Notice that the subfunctions defined here (part1 and
% part2) can only be called from the main function, ex2 5. Trying to run
% the subfunctions from the command window will produce an error.
%
% This function is the same as ex2 4, but broken into subfunctions.

% In the first part, we find the slope.


m = findSlope(pt1,pt2);

% Then we find the y intercept


b = findIntercept(m,pt1);
end

% ======= SUBFUNCTIONS =======


function slope = findSlope(point1,point2)
xValues = [point1(1) point2(1)];
yValues = [point1(2) point2(2)];
slope = (yValues(2) - yValues(1))/(xValues(2) - xValues(1));
end

% ============================
function Yintercept = findIntercept(slope,point)
xValue = point(1);
yValue = point(2);
Yintercept = yValue - slope*xValue;
end

2.2.3 Anonymous Functions

We conclude this chapter with a brief discussion of anonymous functions. Anonymous functions
are functions which are stored in the workspace as a function handle data type, rather than in a
separate M-file. They work in the same manner as regular functions, however they are restricted to

Page 21
CHAPTER 2. MATLAB SCRIPTS AND FUNCTIONS

Figure 2.7: Plot window after running Example 2.6.

a single command and they do not support more than one output (without some additional coding).
They are especially helpful when a complicated expression is used frequently, or in plotting.

Example 2.6 is an example of writing the function sinc(x) = sin(x)/x as an anonymous function.
An anonymous function is declared using the @ symbol, followed by a list of comma separated
inputs in parentheses. The remainder of the line is the command that should be executed given
the input names specified by the anonymous function.

Example 2.6: Example of an anonymous function, used to calculate sinc(x).


%% Anonymous Functions
% Many times, anonymous functions are used to express complicated
% mathematical expressions into a single, consolidate command. It also
% useful for when the closed form expression of the equation is too
% complicated, is unknown, or does not exist. In this example, we will
% compute and plot the sinc function, sinc(x) = sin(x)/x.

% Anonymous function for sinc(x) (vectorized, so we can plot it).


sinc = @(x)sin(x)./x;

% Plot both functions on the same plot


x = -5*pi:0.05:5*pi;
plot(x,sinc(x))
xlabel('Radians')
ylabel('sinc(x)')
grid on, xlim([-5*pi, 5*pi]), ylim([-0.4 1.1])

Page 22
Chapter 3

Program Flow and Input/Output


Control

To allow for more complex analyses, MATLABr implements most of the common program flow
mechanisms, such as loops and conditional statements. Additionally, MATLABr provides support
for different types of input/output operations, such writing to the command window, reading from
files, and writing to files.

In this chapter, we introduce the MATLABr syntax for loops and conditional statements, in
addition to the different relational operators available. We also overview how to write output to
the command window and how to read from and write to files (with an emphasis on files produced
in Microsoft Excelr ). Finally, we provide a list of other, more advanced programming features that
MATLABr is capable of along with links to detailed tutorials.

3.1 Relational Operators

Before discussing any program flow control methods, we briefly mention some of the syntax related
to the relational operators available in MATLABr . Relational operators are the operations used
in boolean algebraic expressions; they evaluate as either TRUE or FALSE. Table 3.1 shows a list
of common relational operators used in MATLABr . A few usage examples of these operators are
shown in Example 3.1. Notice that MATLABr evaluates true expressions as having a value of one.
False expressions are evaluated as having a value of zero.

MATLABr provides short-circuited variations of the & and | , which are denoted as && and || . These
command variations are optimized to return values faster for scalar inputs. This is accomplished by
evaluating the first input, and then deciding if it is necessary to evaluate the second. For example,
the command a || b will first see if a is true. If it is, then there is no reasons to see if b is true
because we already know that result of the expression must be true. Therefore, MATLABr returns
a value of TRUE from the command without determining if b is true.

Page 23
CHAPTER 3. PROGRAM FLOW AND INPUT/OUTPUT CONTROL

Table 3.1: Common relational operators used in MATLABr .

Operator/Command Description
a < b (or a > b) True if a is strictly less than (or strictly greater than) b. If a and b
are matrices, then the operation is performed on every corresponding
element.
a <= b (or a >= b) True if a is at least (or at most) b. If a and b are matrices, then the
operation is performed on every corresponding element.
a == b (or a ~= b) True if a is equal to (or not equal to) b. If a and b are matrices, then
the operation is performed on every corresponding element.
a & b (same as and(a,b)) True if a and b are true. If a and b are matrices, then the operation
is performed on every corresponding element.
a | b (same as or(a,b)) True if a or b is true. If a and b are matrices, then the operation is
performed on every corresponding element.
xor(a,b) True if a is true when b is false, or vice versa. If a and b are matrices,
then the operation is performed on every corresponding element.
~a True if a is false. If a is a matrix, then the operator is performed on
every corresponding element.
any(A) True if at least one element in the input vector A is true. If A is a
matrix, then this function returns a value for each column of A.
all(A) True if all elements in the input vector A is true. If A is a matrix,
then this function returns a value for each column of A.

Example 3.1: Relational operator usage examples.


%% Relation Operator Usage Examples

%% Inequalities
grades = [74 87 90 65 63 55 67];

avgGrade = mean(grades) % mean() computes the average of an array


avgGrade >= 75 % Check if the average of the values in the "grades" array
% is at least 75
avgGrade < 85 % Check if the average is less than 85

%% Composite Expressions
isAvgB = (avgGrade < 89) & (avgGrade >= 80)
isAvgC = (avgGrade < 79) & (avgGrade >= 70)
isAvgF = ~(avgGrade >=60)

%% Usage of any and all commands


didAnyGetA = any(grades >= 90)
didAnyFail = any(grades < 60)
didEveryonePass = all(grades >= 60)

Page 24
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

3.2 Loops

Loops in MATLABr are used to repeat a block of code for a certain number of iterations (for
loops) or until some specified criteria is met (while loops). Their usage is similar to that of other
programming languages.

3.2.1 For Loops

A for loop repeat a block of code for a specified number of times. The current iteration of the
loop is kept track through the use of an indexing variable. Example 3.2 shows two examples of
for loop syntax used in MATLABr . In the first cell, a for loop is used to plot harmonic motion
with different damping ratios. The harmonic motion equation is implemented using an anonymous
function (explained in the previous chapter). The plot of this example is shown in Figure 3.1. In
the second cell, we compute the factorial of a number with a for loop. In both examples, the for
loop is defined with the command for followed by the definition of a index variable that changes
on each iteration of the loop. The values this index variable takes on are also defined. The block
of code to repeat is terminated using the end keyword.
Example 3.2: For loop examples in plotting and in calculations.
%% For Loop Examples

%% Example 1: Looping over a set of values


% Suppose we have a set of lines we would like to plot for a few different
% values of a parameter. This can be easily accomplished by using a for
% loop. Here, we will try and plot the equation for a harmonic oscillator
% with some known damping coefficient, x = eˆ(-zeta/2*t)*(cos(t)+sin(t))

timeVals = 0:0.01:10;
x = @(t,zeta)exp(-zeta/2*t).*(cos(t)+sin(t)); % Harmonic Motion eq
% (with damping)

close all % Close all open figure windows


figure % Open a new figure window

for dampingRatio = [.25 0.75 3] % Different values of zeta


plot(timeVals,x(timeVals,dampingRatio));
hold all % Hold all leaves subsequent plots on the current
% plot window.
end
xlabel('Time (seconds)'), ylabel('Response')
legend('\zeta = 0.25', '\zeta = 0.75', '\zeta = 3.00')

%% Example 2: Using an Incremental Index Counter


% Here, we use a for loop to compute the factorial of N, which is
% N*(N-1)...2*1.
N = 5
factorialN = 1;
for ind = 1:N
factorialN = factorialN * ind;
end
factorialN

Page 25
CHAPTER 3. PROGRAM FLOW AND INPUT/OUTPUT CONTROL

Figure 3.1: Plot window after running the first cell of Example 3.2.

3.2.2 While Loops

In contrast to for loops, while loops repeat a block of code until some condition is satisfied.
Example 3.3 shows an example of the while loop syntax used in MATLABr . Similar to a for
loop, the block of code to be repeated is enclosed between the while and end keywords. The
boolean expression that causes the loop to continue is defined next to the while keyword. Any of
the relational operators in Table 3.1 can be used when defining the loop condition.

Example 3.3: While loop example.


%% While loop example
% In this example, we want to see how many time we have to divide a number
% by 2 to make it less than some value (epsilon). In the example, we will
% start at 15 and figure out how many times we need to divide by 2 to have
% the result be less than 10ˆ-9.

eps = 1e-9;
startingVal = 15;

curVal = startingVal;
count = 0;
while curVal >= eps % While the current values is not less than eps
curVal = curVal/2; % Divide it by 2
count = count + 1; % Increment the iteration count
end

% Display the final values after the loop is done


curVal
count

Page 26
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

3.2.3 Loop Control

Two special keywords exist in the context of a for or while loop. The continue command skips
the remainder of the code contained in the block and moves on to the next iteration of the loop.
The break command forces an early termination of the loop. When nesting loops, these commands
only work under the scope of the current loop in which they are called from.

3.3 Conditional Statements

3.3.1 If-Else Statements

An if-else statement in MATLABr allows for the conditional execution of code in a function or
script based on the evaluation of a boolean expression. Example 3.4 shows a few different ways
that an if-else statement can be implemented. In all of the implementation, the condition code is
surrounded by a combination of the keywords if, elseif, else, and end. The boolean expressions
are placed next to the corresponding if and elseif keywords, and use the relational operators
from Table 3.1.

Example 3.4: If-else statement example implementation.


%% If-else Examples

%% Generate some random value for the examples


randomValue = rand(1); % rand() produces a square matrix of random values
% between 0 and 1.

disp(randomValue) % Display the contents of the random value.

%% Implementation 1: If-else
if randomValue >= 0.5
disp('Value is greater than or equal to 0.5')
else
disp('Value is less than 0.5')
end

%% Implementation 2: If-elseif-else
if and(randomValue >= 0.45, randomValue <= 0.55)
disp('Random value is close to the middle')
elseif randomValue > 0.55
disp('Value too high.')
else
disp('Value is too low')
end

%% Implementation 3: If
if randomValue >= 0.9
disp('Value is actually very high (greater than 0.9)')
end

Page 27
CHAPTER 3. PROGRAM FLOW AND INPUT/OUTPUT CONTROL

3.3.2 Switch-Case Statements

A switch-case statement in MATLABr executes one of several blocks of code based on the value
of an expression. An example is shown in Example 3.5. The main switch expression is placed
next to the switch keyword. The code for each of the possible cases is placed between the case
keywords. The case expressions are placed next to each case keyword. The entire switch-case
statement is terminated with the end keyword. When MATLABr reaches the switch keyword,
it evaluates the corresponding switch expression, which returns either a number or a sting. This
value is then compared to each of the case expressions. Depending on which of the switch and
case expression pairs are equal, a corresponding block of MATLABr code is executed. Notice the
use of an optional otherwise keyword. This defines the code to be executed if none of the case
expressions are matched with the switch expression.

Example 3.5: Switch-case statement example implementation.


%% Switch-case example

caseNumber = 5; % This can be any number

switch caseNumber
case 5
disp('You are using case #5!')
case 10
disp('You are using case #10!')
otherwise
disp('That case doesn''t exist.')
end

3.4 I/O Commands

MATLABr allows for user input and output control in a variety of different ways. The input and
fprintf commands can be used to accept inputs from and write outputs to the command window.
There are also many different ways to read and write from files of various types (tab delimited,
comma separated, and etc.). In this section, we’ll discuss how to read and write data from the
command window and from Microsoft Excelr spreadsheets.

3.4.1 Command window I/O

The MATLABr command window can be used to accept user input using the input command.
The input command accepts a text string as an input to display on the command window. This
string precedes a prompt in which the users specifies in some expression or value, followed by the
enter key. MATLABr evaluates that expression (which may contain variables already in memory),
and stores the result in memory. Calling input with a second input of 's' causes MATLABr save
the entered text as a string, rather than evaluating the expression.

The command window can also be dynamically written to using the fprintf command. In the
simplest case, the first input of fprintf is a string which describes how values should be formatted.

Page 28
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

The remaining inputs are values which are to be displayed. The formatting string can take on a
variety of different forms. In general, the location of a value is specified in the formatting string
using a percent character. We thus direct the reader to the fprintf help documentation for
more information on it’s usage by typing doc fprintf into the command window. We present an
example of command window I/O using input and fprintf in Example 3.6. You are encouraged
to run this example multiple times and observe the output in the command window.

Example 3.6: Example of command window I/O with input and fprintf.
%% Command Window I/O Example

% First clear out the variables and the command window


clear, clc

% Ask for some numbers


num1 = input('Enter a number:: ');
num2 = input('Enter another one:: ');

% Confirm for the user that they are the right numbers to use
% This is done dynamically with fprintf. The escape string '%0.2f'
% corresponds to formatting a number using fixed point precision using 2
% decimal places. Each one of these escape strings matches up with the
% remaining inputs specified by fprintf. The '\n' character tells MATLAB to
% insert a line break into the command window.
fprintf('You entered %0.2f and %0.2f.\n',num1,num2);
response = input('Type yes to confirm, or anything else to quit:: ','s');

if ~strcmpi(response,'yes') % The command strcmpi does a case insensitive


% comparison of two strings to see if they are
% the same.

% If they say anything other than yes, then stop the script
return
end

% Otherwise, take the average of the two numbers and display the result.
numbers = [num1 num2];
numAvg = mean(numbers);

fprintf('The average is %0.4f.\n',numAvg) % Displays average as a fixed


% point number with 4 decimal
% places.

3.4.2 Excel Spreadsheet I/O

MATLABr provides the ability to read and write data to excel files. Reading excel data is done
using xlsread. The xlsread command takes in three inputs: the name of the excel file, the
name of the worksheet from which to extract data from, and the range of cells to extract. Then,
xlsread produces two outputs: the numeric data from the spreadsheet, and the string data from
the spreadsheet. Example 3.7 shows sample code which reads excel data from the spread sheet,
ex3 7.xlsx. The plot windows which appear after running the code are shown in Figure 3.2

Writing to excel spreadsheets is handled by xlswrite. The xlswrite command takes in four
inputs: the name of the excel file to write to, a matrix of the data to write (as it will appear in

Page 29
CHAPTER 3. PROGRAM FLOW AND INPUT/OUTPUT CONTROL

Example 3.7: Implementation of xlsread. Requires the spreadsheet ex3 7.xlsx.


%% Reading from Excel Spreadsheets

%% Loading Excel Data


% The xlsread command takes up to three inputs. The first input is the name
% of the excel sheet you want to read from. The second input is the
% worksheet from which you would like to extract values. The third is the
% range of values you would like to extract (in excel's notation for cell
% ranges).
%
% Data is extracted in two outputs of the command. The first output
% contains the cells which have numeric contents. The second output
% contains the cells with string contents. In this case, the data extracted
% contains only numeric data (excluding the 1st row, which contains
% labels). Hence the result of this command for this spreadsheet is the
% extract of the numeric data and the corresponding column labels..
[salesData, headingText] = xlsread('ex3 7','Sales Log','E:G');

% From the heading text, we can take out the data as follows
transactionQty = salesData(:,1); % First column is the transaction Qty
transactionTotal = salesData(:,3); % Last column is the transaction revenue

% How many transactions were there (use numel to count the number of
% elements in an array)?
numTrans = numel(transactionTotal);

%% Plotting from the Excel Data


% Display a moving average plot of the Transaction Amount (superimpose
% average). The three dots "..." indicate that the command is continued on
% the next line. The moving average is computed with the "smooth" function.
nPtMvngAvg = 3;

close all
figure
plot(1:numTrans,smooth(transactionTotal, nPtMvngAvg, 'moving'),'bo--',...
[1 numTrans],mean(transactionTotal)*[1 1],'k-') % Plot average line

xlabel('Transaction number')
ylabel('Revenue (dollars)')

% Here we place the legend on the graph. The sprintf command works very
% similar to fprintf. Instead of printing output to the command window,
% sprintf produces a MATLAB string.
legend(sprintf('%d-point moving average',nPtMvngAvg),'average')

% Do the same thing for the transaction quantity


figure
plot(1:numTrans,smooth(transactionQty, nPtMvngAvg, 'moving'),'bo--',...
[1 numTrans],mean(transactionQty)*[1 1],'k-') % Plot average line

xlabel('Transaction number')
ylabel('Quantity')
legend(sprintf('%d-point moving average',nPtMvngAvg),'average')

the excel file), the name of the worksheet the data will be placed in, and finally the cell in which
the upper-left corner of the data will start at. The command produces no output by default, and

Page 30
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

(a) Revenue Moving Average (b) Quantity Moving Average

Figure 3.2: Plot windows after running Example 3.7.

it will automatically create any excel files or worksheets if they do not exist. Example 3.8 shows
sample code similar to Example 3.7. Instead of plotting moving averages, the data for the moving
averages are written to separate worksheets in the excel file, ex3 8.xlsx.

Example 3.8: Implementation of xlswrite. Produces the spreadsheet ex3 8.xlsx.


%% Reading from Excel Spreadsheets

%% Loading Excel Data


% This is the same setup as in Ex 3.7
[salesData, headingText] = xlsread('ex3 7','Sales Log','E:G');

transactionQty = salesData(:,1); % First column is the transaction Qty


transactionTotal = salesData(:,3); % Last column is the transaction revenue

numTrans = numel(transactionTotal);

%% Compute Moving Averages


nPtMvngAvg = 3;
QtyMvngAvg = smooth(transactionTotal, nPtMvngAvg, 'moving'); % Col Vector
RevMvngAvg = smooth(transactionQty, nPtMvngAvg, 'moving'); % Col Vector

%% Save results to a new spreadsheet (in two worksheets)


QtyDataToWrite = [(1:numTrans).' QtyMvngAvg]; % Nx2 vector
xlswrite('ex3 8.xlsx',QtyDataToWrite,'Quantity Moving Avg','A1')

RevDataToWrite = [(1:numTrans).' RevMvngAvg]; % Nx2 vector


xlswrite('ex3 8.xlsx',RevDataToWrite,'Revenue Moving Avg','A1')

Note that xlsread and xlswrite take some time to execute, depending on the size of the ex-
cel file. For faster running times, we suggest working with either comma or tab delimited files
using the commands csvread and csvwrite. For more information and examples, consult the
MATLABr help documentation.

Page 31
CHAPTER 3. PROGRAM FLOW AND INPUT/OUTPUT CONTROL

3.5 Miscellaneous Topics

In closing, we outline a few of the other popular programming constructs that MATLABr offers.
For more information regarding these topics and detailed usage examples, see the MATLABr help
documentation.

ˆ Object Oriented Programming: In addition to scripts and functions, MATLABr offers


the ability to create custom object-oriented programs. These custom object classes become
increasingly useful as the complexity of the task and data structures increase. For more infor-
mation, see the MATLABr help documentation at MATLAB\User’s Guide\Object-Oriented
Programming.

ˆ Regular Expressions and Text Replacement Strings: Regular expressions are special
character strings that define a string pattern. They can then be used to search for that
string pattern amongst a larger set of text (e.g., using strfind), and optionally perform
text replacement (e.g., using regexprep). For more information, see the MATLABr help
documentation at MATLAB\User’s Guide\Programming Fundamentals\Language\Program
Components\Regular Expressions.

ˆ Dynamic Command Execution: MATLABr can be used to dynamically execute com-


mands. MATLABr command strings are generated using sprintf and then passed to the
eval command, which evaluates the corresponding string in the command window. For more
information, see the MATLABr help documentation at MATLAB\Functions\Programming
and Data Types\Characters and Strings\eval

ˆ Executing Shell Commands: Shell commands can also be executed from inside MATLABr ,
using the system command. For more information, see the MATLABr help documentation
at MATLAB\Functions\Desktop Tools and Development Environment\Command Window
and History\system.

ˆ Error Handling and Catching: Customized error and warning messages can be developed
using the error and warning functions. The occurrence of an error can also be used to to
trigger certain blocks of code within a script or function using try/catch statements. For more
information, see the MATLABr help documentation at MATLAB\Functions\Programming
and Data Types\Programming in MATLAB\Control Flow.

ˆ Graphical User Interfaces: It is also possible to create graphical user interfaces (GUIs)
in MATLABr using figure windows. GUI layout designs are created using the guide com-
mand and call back functions. For a detailed tutorial, see MATLAB\User’s Guide\Creating
Graphical User Interfaces\Introduction to Creating GUIs\About GUIs in MATLAB
Software\Ways to Build MATLAB GUIs.

Page 32
Chapter 4

Symbolic Math

The Symbolic Math Toolbox— is an add on which can be purchased alongside of MATLABr .
It is used for solving and manipulating symbolic equations, and in some cases for performing
variable precision arithmetic. The goal of this chapter is to showcase the basic functionality of
the MATLABr symbolic toolbox. We start by introducing how symbolic variables are constructed
and used to produce analytic expressions. Then, we discuss the use of symbolic variables in more
complicated operations such as root finding, determining the inverse of a function, and solving
differential equations. We finally conclude this chapter with a discussion on how to generate plots
and anonymous functions using symbolic expressions.

4.1 Symbolic Variables and Arithmetic

The variables of a symbolic equation are defined in the MATLABr workspace as symbolic objects.
The symbolic object data type is similar to the numeric data type, in the sense that both make use
of the standard mathematical operations (e.g., addition, multiplication, exponentiation, etc.). The
main difference is that an expression involving numeric data types will evaluate to a value, whereas
the symbolic objects will evaluate to some simplified expression.

4.1.1 Working with Symbolic Objects

Symbolic objects are created with either the sym or syms commands. The sym command is useful for
creating symbolic objects of expressions involving only numbers. The syms command is useful for
creating symbolic objects for each of the variables present in an equation. Example 4.1 shows a few
different symbolic object creation methods. As you execute some of the commands in Example 4.1,
you’ll notice that the symbolic toolbox attempts to simplify the expressions. For the most part,
any arithmetic command which would work on a numeric data type in MATLABr will also work
on a symbolic object (e.g., sin, exp, mod, conj, and etc.).

Page 33
CHAPTER 4. SYMBOLIC MATH

Example 4.1: Creating symbolic objects with sym and syms.


%% Introduction to Symbolic Objects

%% Symbolic Expressions of Numbers


% For expressions consisting of just numbers, we construct a symbolic
% variable using the sym command. The syms command take a single string
% input, which represents how one would type the expression into the MATLAB
% command window. If possible, sym will try to reduce the expression when
% it saves the result in memory

% Run the following commands unsurpressed and observe the output in the
% command window
sym('sqrt(5)+sqrt(125)')
sym('sqrt(4)/2+5ˆ2*(sqrt(5)+2)')
goldenRatio = sym('(1+sqrt(5))/2')
goldenRatio/5+2*goldenRatio/7-goldenRatioˆ2

%% Symbolic Expressions of Variables


% The syms command can be used to create a quick list of variables to be
% used in a symbolic expression.
syms x y z
sampleExression = x/3+x-y*y+y*(y/3-y/4)
anotherExpression = sin(x)+sin(x)

4.1.2 Algebraic Manipulations

The symbolic toolbox gives access to a variety of different functions for algebraic manipulation.
Example 4.2 showcases the usage of the expand, factor, and simplify functions. The expand
function will expand out a polynomial, trigonometric, or logarithmic function. The factor function
will factor either a polynomial into a product of sums or a scalar into its prime factorization. The
simplify function will attempt to reduce an expression to the simplest form possible by making
use of expand, factor, and common mathematical identities.

Example 4.3 showcases how the symbolic toolbox can be used when performing analyses of linear
systems. The eig and poly functions yield the eigenvalues and characteristic polynomials for a
given matrix. The colspace and diag yield the column space of the matrix and the diagonal
elements. Note that all four of these functions can also be used for non-symbolic matrices.

4.1.3 Limits, Integration, and Differentiation

The symbolic toolbox allows for taking the limit of, differentiating, and integrating a symbolic
function. These three operations are achieved through the limit, diff, and int commands.
Usage examples of these three commands are shown in Example 4.4. Note that the int function
can be used to evaluate a definite or indefinite integral of a symbolic function. Furthermore, a
symbolic variable can be chosen for limit, diff, or int to perform the operation with respect to.
For more information, see the MATLABr help documentation on any of these three functions.

Page 34
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

Example 4.2: Algebraic manipulation and simplification of symbolic expressions.


%% Algebraic Manipulation with Symbolic Objects

%% Expanding Expressions
% These operations make use of the expand function. Run them in the command
% window and observe the output which is produce by each.
syms x y

expand( (xˆ2+1)*(xˆ2-1) )
expand( sin(2*x) )
expand( exp(x+y) )

expand( log(x/y) )
expand( log(x/y), 'IgnoreAnalyticConstraints',true) % Special option to
% expand logs. See
% "doc expand" for more
% details

%% Factoring Expressions and Values


% Examples of using the factor function. Note that x and y are still
% defined as symbolic variables.

factor( xˆ2+2*x*y+yˆ2 ) % An example of factoring a polynomial


factor( sym('26772') ) % An example of a prime factorization

%% General Simplification
% Examples of using the simplify command.

simplify( (x+3)ˆ2 + (x+3)ˆ3 )


simplify(sin(x)ˆ2 + cos(x)ˆ2)
simplify( 1/(cot(x)+tan(x)) )

Example 4.3: Examples of using the symbolic toolbox to perform linear algebra manipulations.
%% Linear Algebra Symbolic Operations

%% Define a symbolic matrix and perform analysis


syms a
A = [1 a; -a a]

diag(A) % Diagonal elements?


eig(A) % eigenvalues?
colspace(A) % Column space?
poly(A) % Characteristic equation

%% Define a numeric matrix, but give exact answers


A2 = sym('[2, 2; 1, -2]')
poly(A2)
eig(A2)

4.2 Advanced Symbolic Analysis

The symbolic toolbox provides functionality for more sophisticated manipulations, such as evalu-
ating the composition of functions or determining the inverse of a function. It also provides the
ability to solve for the roots of an equation, solve a system of differential equations, and perform

Page 35
CHAPTER 4. SYMBOLIC MATH

Example 4.4: Examples of using the symbolic toolbox to assist in calculus analyses.
%% Calculus with the Symbolic Toolbox

%% Evaluating Limits
% The limit function takes three inputs: a sybolic function, the symbolic
% variable to evaluate the limit for, and the value of symbolic variable at
% the limit.
syms x y n

limit( 100/(xˆ2+5) ,x,Inf)


limit( sqrt((xˆ3-7*x)/(4*xˆ3+5)) ,x,Inf)
limit( (xˆ-1+0.5)/(xˆ3+8),x,-1 )

%% Integration Examples
% The int function derives a closed form expression for the indefinite
% integral of a symbolic function (if it exists). The definite integral
% between two values can be computed by passing those two
% corresponding values as a second and third input to int.
int(xˆn) % Indefinite integral
int((xˆ(1/5)+2)ˆ-1)

syms a b
int(cos(x),a,b) % Definite integrals
int(cos(x),0,pi/2)

%% Differentiation examples
% The diff function will differentiate a symbolic function.
diff(xˆn)
diff(sin(x))
diff(xˆ4/(x+1))

various integral transforms (e.g., Fourier and Laplace transforms).

4.2.1 Functional Inverses and Compositions

The MATLABr symbolic toolbox allows for complex functional operations, such as determining
composite functions and function inverses. These operations are realized with the compose and
finverse commands. Usage examples of these commands are shown in Example 4.5. Note that
for the finverse command, an optional input can be used to specify the variable that the inverse
should be performed with respect to. By default, these commands may not produce the most
simplified representation of the final expression. In some cases, the simplify can be used to
further reduce the size of the expressions found when using compose and finverse. For more
information, see the MATLABr help documentation on these two functions.

4.2.2 Solving Systems of Polynomial Equations

The solve function provides a mechanism for determining the solution set for a system of polyno-
mial equations. This function can also be used to find the roots of a single polynomial. The general
syntax of solve is shown in Example 4.6. Notice the use of == over = when specifying a system of
equations. For more detailed examples, see the MATLABr help documentation for solve.

Page 36
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

Example 4.5: Functional composition and inverse with the symbolic toolbox.
%% Example of Symbolic Function Manipulation

%% Functional Inverses
% Try running some of these in the command window. For more information,
% type "doc finverse" in the command window.
syms x y

finverse( cos(x) )
finverse( 2*log(x + 1) )
finverse( x*exp(y/2) , x ) % Inverse w.r.t. x
finverse( x*exp(y/2) , y ) % Inverse w.r.t. y

%% Functional Compositions
% Recall that a functional composition involves substituting the output of
% one function into another. Try running some of these in the command
% window. For more information, type "doc compose" in the command window.
f = tan(x);
g = (1 + xˆ2)ˆ-1;
h = 1/x;

f1 = compose(h,g) % Sub g(x) into h(x)


f2 = compose(g,h) % Sub h(x) into g(x)
f3 = compose(g,f) % Sub f(x) into g(x)

simplifiedF3 = simplify(f3) % Use trig rules to simplify g(f(x))

Example 4.6: Solving systems of polynomial equations with the symbolic toolbox.
%% Using the "solve" command

%% Solving for roots of a polynomial


% Save a polynomial expression as a symbolic variable, then use the solve
% command, followed by what the expression is equal to.
syms x
f = 4*xˆ2 -15*x + 9;
solve(f == 0) % Solve for the roots
factor(f) % Compare to what happens when we factor

%% Solving a system of equations


% Solve can take in multiple equations as inputs. In this case, solve will
% attempt to find a solution to the specified system of equations. Notice
% the use of "==" over "=".

% System of linear equations


[x1 y1] = solve(x+2*y == 4, x-2*y == 2)

% System of polynomial equations


[x2 y2] = solve(xˆ2 + yˆ2/4 == 1, y == x+1)

4.2.3 Solving Systems Differential Equations

Similar to solve, the function dsolve can be used to solve systems of differential equations.
Example 4.7 shows how dsolve can be used to solve systems of first order equations. The command
syms y1(t) can be used to create a symbolic function y which is a function of some symbolic

Page 37
CHAPTER 4. SYMBOLIC MATH

variable t. Derivatives are specified using the diff command. If the boundary conditions are not
specified, then dsolve will return integration constants. For more examples of solving systems
which have higher order derivatives or non-linear differential equations, see the MATLABr help
documentation for dsolve.

Example 4.7: Solving systems of differential equations with the symbolic toolbox.
%% Solving systems of differential equations with "dsolve"

%% Single Equation Systems


syms y1(t) y2(t) t a % Create symbolic variables.
% y1(t) and y2(t) are functions of t.
% Note that we didn't have to create t as a
% symbolic variable to make y1(t) and y2(t).

dsolve( diff(y1) == a*y1 ) % Solves the diff eq dy1/dt = a*y1(t)


dsolve( diff(y1) == t*y1 ) % Solves the diff eq dy1/dt = t*y1(t)

% Try the same two equations, but with boundary conditions


dsolve( diff(y1) == a*y1 ,y1(0) == 5)
dsolve( diff(y1) == t*y1 ,y1(1) == 1)

% A second order differential equation, with boundary conditions


Dy1 = diff(y1);
D2y1 = diff(y1,2);
dsolve( D2y1 + 3*Dy1 + 2*y1 == 2,...
y1(0) == 0, Dy1(0) == 0)

%% Multiple Equation Systems, first order system


% Try solving a first order system with initial conditions
[y1Sol y2Sol] = dsolve(diff(y1) == 2*y1 + y2, ...
diff(y2) == -y1 + 2*y2,...
y1(0) == 1, y2(0) == 3)

4.2.4 Transforms of Symbolic Equations

The MATLABr symbolic toolbox also implements a few of the popular integral transforms. The
laplace and fourier commands determine the Laplace and Fourier transforms of a signal. The
commands for the inverse Laplace and Fourier transforms are ilaplace and ifourier. Exam-
ple 4.8 shows the syntax of the laplace and fourier symbolic transformations. Notice that the
step and impulse functions are defined in MATLABr using the heaviside and dirac commands.

4.3 Plotting with Symbolic Expressions

The symbolic toolbox offers a suite of commands for creating plots from symbolic objects. A
selection of these commands are shown in Example 4.9. The ezplot command creates a 2D
plot using a symbolic function of one variable, or two symbolic functions of a single parame-
ter. The ezsurf command creates a 3D surface using a symbolic function of two variables, or
three symbolic functions of two parameters. The default limits on the domain for each com-
mand is 0 to 2π. More examples of symbolic object plotting functions can be found in the

Page 38
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

Example 4.8: Laplace and Fourier transforms with the symbolic toolbox.
%% Symbolic Integral Transforms

%% Laplace Transform and Inverse Transform


syms t s w % Default variable names for time, the laplace variable, and the
% fourier variable.

F = heaviside(t); % heaviside <--> Step function


Flaplace = laplace(F)

Fout = Flaplace * (1/(s+1)) % System transfer function


ilaplace(Fout) % Result

%% Fourier Transform and Inverse Transform


fourier( cos(3*t) )
ifourier( pi*(dirac(w-7)+dirac(w+7)) ) % By default, this is in complex
% exponential format

simplify(ifourier( pi*(dirac(w-7)+dirac(w+7)) )) % This put it back in as


% sines and cosines

MATLABr help documentation under Symbolic Math Toolbox\User’s Guide\Using Symbolic


Math Toolbox Software\Using Graphics.

4.4 Generating Anonymous Functions

The matlabFunction command can generate an anonymous function handle from any symbolic
expression. By default, the anonymous function will be vectorized so that it will calculate array
inputs element-by-element. This is particularly useful when wanting to work with a derived expres-
sion from a simpler expression, especially when the derived expression is hard to write in closed
form (e.g., taking a complicated integral or derivative). The syntax is fairly straightforward, and
is exemplified in Example 4.10.

Page 39
CHAPTER 4. SYMBOLIC MATH

Example 4.9: Creating 2D and 3D plots from symbolic objects.


%% Plotting symbolic functions
% For each of the examples, create the symbolic variables using SYMS, and
% then run one command at a time to observe the results.
syms t u x y z

%% Plot a sine wave (default domain is -2pi to 2pi)


ezplot(sin(t))

%% Plot a logistic function, over the domain 0 to 10


ezplot( 1-(1+exp(t-5))ˆ-1 ,[0 10])

%% Plot a 2D circle of radius 4


ezplot( xˆ2 + yˆ2 - 16 ) % This syntax will produce the plot of xˆ2 + yˆ2
% - 16 = 0 (i.e., xˆ2 + yˆ2 = 16). The x and y
% limits are -2pi to 2pi by default

%% Do a 2D parametric plot
f1 = cos(t)-cos(5*t)ˆ3;
f2 = sin(t)-sin(5*t)ˆ3;

ezplot(f1,f2) % Plot f2 vs f1 for t from 0 to 2pi

%% Plot a sphere (the inside equation is set equal to zero)


ezsurf( exp(-0.075*y)*xˆ2 + 5*sin(y)ˆ2 - 1 )

%% Make a 3D torus ring via a 3d parametric plot


fx = cos(t)*(2+0.75*cos(u));
fy = sin(t)*(2+0.75*cos(u));
fz = 0.5*sin(u);

ezsurf(fx,fy,fz)

Example 4.10: Creating anonymous functions from symbolic expressions.


%% Generating Anonymous Functions from Symbolic Objects
% This example creates a function with symbolic variables, differentiates
% it using the symbolic toolbox, makes an anonymous function for each one,
% and then plots both functions on a single graph.
syms x
f = sin(x)*cos(x)/(x+1)ˆ2;
Df = diff(f);

fFunc = matlabFunction(f);
DfFunc = matlabFunction(Df);

xVals = 0:0.05:7;
plot(xVals,fFunc(xVals),xVals,DfFunc(xVals))
xlabel('x'), ylabel('Values'),legend('f','df/dt')

Page 40
Chapter 5

Selected Topics and Examples

For the remainder of the course, we will be focusing on how a selection of electrical engineering
calculations and analyses can be performed in MATLABr . In this chapter, we start by discussing
how MATLABr can be used to perform linear regression and polynomial curve fitting. We then
discuss the various numerical methods available for solving differential equations and for performing
frequency domain analysis. Note that all of the commands discussed in this chapter are available
in the MATLABr base installation package.

5.1 Linear Regression and Curve Fitting

Curve fitting and linear regression is handled in MATLABr using the polyfit command. This
command takes in a set of x and y coordinates, in addition to a non-negative integer which specifies
the degree of the polynomial that the coordinates should be fitted to. The result is a set of
coefficients for a degree n polynomial that best fits the coordinate pairs in the least squares sense.
These coefficients can be used to evaluate the output of the corresponding polynomial using the
polyval command.

Example 5.1 showcases the syntax of the polyfit and polyval commands. In this example,
random data is generated according to some deterministic relationship. Gaussian white noise with
some fixed variance is then added to the y-coordinates of the data. We fit the resulting noisy data
to a linear line and to a 10th degree polynomial using polyfit. We then plot the data, both of the
fitted curves, and the relationship from which the data was generated. In this example, the linear
relationship is a better fit for the data even though the higher order polynomial exhibits a lower
mean squared error (by inspection of Figure 5.2)

5.2 Numerically Solving Differential Equations

MATLABr offers seven different functions for solving initial value problems involving ordinary
differential equations (ODEs). For the scope of this handbook, we will focus on the most commonly

Page 41
CHAPTER 5. SELECTED TOPICS AND EXAMPLES

Example 5.1: Using polyfit and polyval for curve fitting.


%% Examples using polyfit and polyval

%% Generate some data to use

% Data set: y = 3*t-4 for fixed t values


tVals = (0:0.1:4).'; % Generate a column vector of values
yVals = -3*tVals-4;

% Add 0 mean Gaussian noise with a variance equal to 64.


yValsNoise = yVals + 8*randn(size(yVals));

%% Estimate the relationship with polyfit


pLin = polyfit(tVals,yValsNoise,1); % 1st order (linear)
pQuad = polyfit(tVals,yValsNoise,10); % 10th order (overfitted)

%% Show both fits


% Sorting ensures that the lines show up right
plot(tVals,yValsNoise,'bo',...
tVals,yVals,'k-',...
tVals,polyval(pLin,tVals),'r--',...
tVals,polyval(pQuad,tVals),'g--')

legend('Simulated Relationship',...
'True Relationship',...
'Linear Fit',...
'10ˆ{th} order polynomial fit')

xlim([0 4]), ylim([-35 20])


xlabel('t'),ylabel('y(t) with noise')

Figure 5.1: Curve fitting results after running Example 5.1.

Page 42
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

used ODE solver, known as ode45. ODE45 is one of the most basic ODE solvers to understand,
and it is relatively accurate with respect to a wide range of solution curve types.

5.2.1 ODE45 Syntax

ODE45 is implemented with the following steps:

ˆ Express the differential equation in terms of it’s first order derivative (or as a system of first
order derivatives).

ˆ Make a MATLABr function of (1). Note that this function must have two inputs: (t,y).
The order of these inputs matters! The first denotes time steps, where as the second
denotes the output of the solution y(t). The function can be created either in an M-file, or
by using anonymous functions. Note that it does not need to be vectorized in order to work.

ˆ Create a function handle of (2). If the function is in a separate file, this is done by typing
an @ symbol followed by the name of the function. This is not necessary if an anonymous
function was used in (2).

ˆ Call ODE45 with three inputs: the function handle of (3), a two element vector containing
the time span to produce the solution over, and the initial condition of the solver. ODE45
yields two outputs: an array of time values, and the solution of the differential equation.

A simple example of using ode45 with an anonymous function is shown in Example 5.2. Again,
notice the order of the inputs (t,y) for the anonymous function. The numerical solution of the
ODE given in Example 5.2 is shown in Figure 5.2.

Example 5.2: Example using ODE45 with an anonymous function.


%% Working with ODE45

%% Define a differential equation as a function


% This can be done either with an anonymous function, or with an m-file
% function. All of MATLAB's ODE solvers accept only first-order
% differential equations. To work with higher order differential equations,
% you must rewrite them into a system of linear differential equations.
ydot = @(t,y)y*(1-y);

%% Call ODE45
[t y] = ode45(ydot, [0 10], 0.01);

%% Plot the results


plot(t,y,'bo-')
grid on, xlabel('Time'), ylabel('y(t)')

5.2.2 Solving Piecewise Differential Equations

MATLABr ’s family of ODE solvers are versatile, in the sense that they only require MATLABr func-
tions to operate. As long as the function contains the correct inputs and outputs, there are no

Page 43
CHAPTER 5. SELECTED TOPICS AND EXAMPLES

Figure 5.2: Numerical solution of Example 5.2 using ode45.

restrictions on the types of commands or operations that can be performed inside of the function.
For example, if-else statements can be used to implement a piecewise differential equation. Consider
the first order initial value problem given by
(
dy(t) −0.2y(t) + 20 t ≤ 30
= , y(0) = 0. (5.1)
dt −0.1y(t) otherwise

ODE45 is implemented for this initial value problem in Example 5.3. The M-file function that
implements this differential equation for use with ODE45 is given in Example 5.4. Notice in
Example 5.3 that the name of the M-file is preceded by an @ symbol. This allows the contents of
the M-file to be passed into ODE45 as a function handle. The solution is shown in Figure 5.4.

Example 5.3: Example using ODE45 to solve a piecewise differential equation.


%% ODE45 and Piecewise Differential Equations

%% Call ODE45 on the external m-file function


% Here, the m-file is ex5 4.m. Notice the inclusion of the @ symbol.
[t y] = ode45(@ex5 5, [0 60], 0);

%% Plot the results


plot(t,y,'bo-')
grid on, xlabel('Time'), ylabel('y(t)')

Example 5.4: M-file function of the differential equation used in Example 5.3.
function ydot = ex5 4(t,y)
if t <= 30
ydot = -0.2*y+20;
else
ydot = -0.1*y;
end

Page 44
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

Figure 5.3: Numerical solution of Example 5.3 (piecewise differential equation) using ode45.

5.2.3 Solving Systems of Differential Equations

To solve a system of first order differential equations with ODE45, we create a function M-file of the
system by letting the solution variable and the derivative of the solution variable be column vectors.
We briefly illustrate this to numerically calculate the solution of a Lorentz attractor, defined by
the following initial value problem

dx1 (t)
= σ(x2 (t) − x1 (t))
dt
dx2 (t)
= x1 (t)(ρ − x3 (t)) − x2 (t) (5.2)
dt
dx3 (t)
= x1 (t)x2 (t) − βx3 (t)
dt

where in this case, σ = 10, ρ = 28, and β = 8/3. ODE45 is implemented for this initial value
problem in Example 5.5. The M-file function that implements this differential equation for use
with ODE45 is given in Example 5.5. Notice that the output of the function Example 5.6 is
designated as a column vector (based on preallocating space using the zeros command). The
solution is shown in Figure 5.4.

Notice that we have shown multiple plot windows in a single figure with use of the subplot
command. This functionality may prove useful if you are working with similar plots and would like
to create a custom layout in a single figure window. For more detailed usage examples of subplot,
see the MATLABr help documentation.

Page 45
CHAPTER 5. SELECTED TOPICS AND EXAMPLES

Example 5.5: Example using ODE45 to solve a system of differential equations.


%% ODE45 and Systems of Differential Equations

%% Call ODE45 on the external m-file function


% Here, the m-file is ex5 6.m and describes a Lorentz attractor.
[t x] = ode45(@ex5 6, [0 10], [15 10 10]);

%% Plot the results


subplot(3,2,1), plot(t,x(:,1))
grid on, xlabel('Time'), ylabel('x 1 Component')

subplot(3,2,3), plot(t,x(:,2))
grid on, xlabel('Time'), ylabel('x 2 Component')

subplot(3,2,5), plot(t,x(:,3))
grid on, xlabel('Time'), ylabel('x 3 Component')

subplot(3,2,[2 4 6]), plot3(x(:,1),x(:,2),x(:,3))


grid on, xlabel('x 1'), ylabel('x 2'), zlabel('x 3')

Example 5.6: M-file function of the differential equation used in Example 5.5.
function xdot = ex5 6(t,x)
sig = 10; rho = 28; beta = 8/3; % Parameters

xdot = zeros(3,1); % Preallocate space for the output (col vector)


xdot(1) = sig*(x(2)-x(1));
xdot(2) = x(1)*(rho-x(3)) - x(2);
xdot(3) = x(1)*x(2) - beta*x(3);

Figure 5.4: Numerical solution of Example 5.5 (Lorentz attractor) using ode45.

Page 46
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

Figure 5.5: Time and frequency domain representation of the signal created in Example 5.7.

5.3 Frequency Domain Analysis

MATLABr implements a fast Fourier transform using the fft command. We introduce a simple
example of using fft in Example 5.7. A signal with multiple frequency components is created
by summing sinusoids with different frequencies and magnitudes. White noise is added to the
signal using the randn function. The FFT power of the resulting signal is calculated using fft and
plotted. For more detailed examples, see the MATLABr help documentation under MATLAB\User’s
Guide\Mathematical\Fourier Transforms\Fast Fourier Transform (FFT).

Example 5.7: An example of frequency analysis in MATLABr with fft.


%% Generate some data with a fixed sampling rate
sampRate = 10e3; dT = 1/sampRate;

% We're going to superimpose 4 sinusoids at 4 different frequencies with


% different magnitudes
f1 = 35; f2 = 65; f3 = 100; f4 = 125;
mag1 = 0.25; mag2 = 0.3; mag3 = 0.2; mag4 = 0.2;

% Generate time up to 3 cycles of the max freq in the signal.


t = 0:dT:10;
sig = mag1*sin(2*pi*f1*t) + mag2*sin(2*pi*f2*t) + ...
mag3*sin(2*pi*f3*t) + mag4*sin(2*pi*f4*t) +...
6*randn(size(t)); % Add in some white noise to make it look real

%% Generate and plot the FFT power of this signal


sigFFT = fft(sig); FFTpower = abs(sigFFT).ˆ2/length(sigFFT);

N = length(sigFFT);
freqValues = (0:N-1)*(sampRate/N);

subplot(1,2,1), plot(t,sig)
xlabel('Time (seconds)'), ylabel('Amplitude'), grid on

subplot(1,2,2), plot(freqValues,FFTpower)
xlim([0 250]), xlabel('Frequency (Hz)'), ylabel('FFT Power'), grid on

Page 47
Page 48
Chapter 6

Additional MATLABr Toolboxes and


Resources

MATLABr has a variety of toolboxes and add-ons that can be added to its base installation to
assist with a variety of engineering and scientific tasks. We briefly discuss a few of these below. For
more details or specific usage examples, see the Getting Started topics under any of the toolboxes
or add-ons in the MATLABr help documentation.

ˆ Symbolic Math Toolbox and MuPAD: We discussed the Symbolic Math Toolbox at
length in Chapter 4. One additional feature of the toolbox are MuPAD notebooks (Fig-
ure 6.1). MuPAD notebooks are separate subprograms of MATLABr that allow for LaTeX-
like typesetting using the symbolic toolbox, in addition to the generation of various specialized
types of plots. All of the symbolic object operations discussed in Chapter 4 can be performed
in a MuPAD notebook, with a few difference in syntax from the MATLABr command win-
dow or a script. A MuPAD notebook is opened by typing mupad in the command window.
Introductory MuPAD tutorials can be found in the MATLABr help documentation under
Symbolic Math Toolbox\User’s Guide\MuPAD in Symbolic Math Toolbox.

ˆ Control Systems Toolbox: The Control Systems Toolbox provides optimized algorithms
for analyzing, designing, and fine-tuning control systems. Systems can be specified as transfer
functions, in state-space, by zeros and poles, or by a frequency response. In these formats, the
Control Systems Toolbox provides an easy-to-use interface for obtaining step responses, Bode
plots, and root-locus diagrams. Design tools and applications are also available to quickly
prototype state feedback, PID, and LQR controllers (to name a few).

ˆ Simulink: Simulink is a graphical programming environment built on MATLABr that uses


block diagrams for multidomain simulation and Model-Based design. It allows the user to
model linear and non-linear control systems using transfer functions, integrators, and ampli-
fiers (to name a few). Simulink can also be used to generate MATLABr code and to design,
test, or verify an embedded system.

ˆ DSP System Toolbox: The DSP System Toolbox provides MATLABr functions, objects,
and Simulink blocks for designing and simulating signal processing systems. The toolbox

Page 49
CHAPTER 6. ADDITIONAL MATLABr TOOLBOXES AND RESOURCES

Figure 6.1: Example commands in the MuPAD interface.

includes functions and applications to assist in designing FIR and IIR filters, in addition
to specialized implementations of FFTs and methods for multirate processing. It also con-
tains functions to assist in implementing filters in a computationally efficient manner, and to
simulate floating-point digital filters.

ˆ Communications System Toolbox: The Communications System Toolbox provides a


large variety of MATLABr functions and objects for designing, simulating, and analyzing
wireless communications systems. Specifically, there are functions which implement popular
methods source coding, channel coding, bit interleaving, modulation, and channel modeling
(to name a few). This toolbox can be used to model and simulate many industry standard
communication techniques (e.g., OFDM, OFDMA, and MIMO), in addition to providing a
means for auto-generating C or HDL code.

ˆ Image Processing Toolbox: The Image Processing Toolbox provides MATLABr support
for a large set of reference-standard algorithms and functions for image processing and anal-
ysis. The commands provided by this toolbox make it straight forward to perform image
segmentation, enhancement, noise reduction, and geometric transformations. The toolbox

Page 50
A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

also provides tools for blob analysis and for implementing convolution kernels.

ˆ Parallel Computing Toolbox: The Parallel Computing Toolbox allows for the develop-
ment of MATLABr code that executes in parallel on multi-core computers, Graphics Pro-
cessing Units (GPUs), or computer clusters. The toolbox provides high-level constructs for
realizing parallel code execution, such as parallel for-loops, specialized array types, and par-
allelized numerical algorithms.

ˆ Instrument Control Toolbox: The Instrument Control Toolbox provides command sets for
controlling various measurement and testing instruments from MATLABr (e.g., oscilloscopes,
function generators, signal analyzers, power supplies, power meters, and etc.). The command
sets provided by this toolbox all operate over industry standard instrument drivers, such as
IVI, VXI, or text-based SCPI commands, and are also able to communicate with devices
using GPIB, VISA, TCP/IP, and UDP protocols.

ˆ Statistics Toolbox: MATLABr ’s Statistic Toolbox provides access to statistics and ma-
chine learning algorithms for analyzing and modeling data. The functions provided by this
toolbox allow for the design and implementation of Monte Carlo algorithms, parametric and
non-parametric classifiers, hidden Markov models, support vector machines, and hypothesis
tests. The toolbox also provides applications to assist in exploratory data analysis.

Page 51

Vous aimerez peut-être aussi