© All Rights Reserved

0 views

© All Rights Reserved

- 7 Electre Method
- Mathematics_Value Based Question_12
- Thaddeus H.black Derivations
- Octave-Matlab-Tutorial
- MATLAB Basic Commands.pdf
- Cp Lab Manual
- part 1
- Subplot Matlab
- maltab graphics
- Intro to Matlab
- CBSE 11-12 MAths Syllabus
- DirectFileTopicDownload (11).pdf
- IITJEEPCM
- datasheet mat lab.pdf
- MathsI sallybus.pdf
- Analisis Trial Mm 2015 (p2)
- matlab1
- Notice_Engl_NDA_NA _I_ Exam_ 2017_0.pdf
- MATLABsumtum
- lab02

You are on page 1of 65

Presented by:

Dr. Thomas Chmielewski, Ph.D.

Donald J. Bucci

on

Saturday, June 7th, 2014

Department of Electrical and Computer Institute of Electrical and Electronics

Engineering Engineers (IEEE)

Drexel University Philadelphia Section

Revision History

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.

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

Page vi

List of Tables

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

Page vii

Page viii

List of Figures

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.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.6 The published HTML document using the cell mode script with markup, given in

Example 2.3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

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

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

Page x

List of Examples

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

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

Page xi

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

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

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.

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

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.

+,-,*,/ 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)

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

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.

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.

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

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

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.

A11 = [1 2; 3 4];

A12 = zeros(2,2);

A21 = ones(2,2);

A22 = A11.';

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)

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.

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

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!

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

A = myMatrix;

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.

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)

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.

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)

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.

xComponents = [0 0 2 2 4];

yComponents = [0 2 2 0 0];

plot(xComponents, yComponents)

Page 7

CHAPTER 1. INTRODUCTION TO MATLABr

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.

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)

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

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

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.

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

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.

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.

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

% PLOTTING SOME FUNCTIONS

% This is an example script file with some comments. It uses the same

% content from Example 1.9 in the text.

xValues = -pi:0.1:pi;

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

grid off

xlabel('Radians')

ylabel('Functional Values')

legend('y 1','y 2')

xlim([-pi pi])

ylim([-1.2 1.2])

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.

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

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!

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

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)

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

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

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.

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.

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

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

%

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

% 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.

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

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

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

Page 20

A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

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

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.

m = findSlope(pt1,pt2);

b = findIntercept(m,pt1);

end

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

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

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.

%% 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.

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

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

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.

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

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.

%% Relation Operator Usage Examples

%% Inequalities

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

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)

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.

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

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

figure % Open a new figure window

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

% 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.

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.

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

curVal

count

Page 26

A HANDS ON INTRODUCTION TO MATLABr (SECOND EDITION)

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.

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.

%% If-else Examples

randomValue = rand(1); % rand() produces a square matrix of random values

% between 0 and 1.

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

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.

%% Switch-case example

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

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.

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

clear, clc

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

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

% point number with 4 decimal

% places.

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

%% Reading from Excel Spreadsheets

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

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

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)

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.

%% Reading from Excel Spreadsheets

% This is the same setup as in Ex 3.7

[salesData, headingText] = xlsread('ex3 7','Sales Log','E:G');

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

numTrans = numel(transactionTotal);

nPtMvngAvg = 3;

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

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

QtyDataToWrite = [(1:numTrans).' QtyMvngAvg]; % Nx2 vector

xlswrite('ex3 8.xlsx',QtyDataToWrite,'Quantity Moving Avg','A1')

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

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.

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.

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.

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.

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

%% Introduction to Symbolic Objects

% 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

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

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.

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)

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

% Examples of using the factor function. Note that x and y are still

% defined as symbolic variables.

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

%% General Simplification

% Examples of using the simplify command.

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

syms a

A = [1 a; -a a]

eig(A) % eigenvalues?

colspace(A) % Column space?

poly(A) % Characteristic equation

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

poly(A2)

eig(A2)

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

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.

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;

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

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

Example 4.6: Solving systems of polynomial equations with the symbolic toolbox.

%% Using the "solve" command

% 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

% 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 "=".

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

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

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"

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) == t*y1 ) % Solves the diff eq dy1/dt = t*y1(t)

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

dsolve( diff(y1) == t*y1 ,y1(1) == 1)

Dy1 = diff(y1);

D2y1 = diff(y1,2);

dsolve( D2y1 + 3*Dy1 + 2*y1 == 2,...

y1(0) == 0, Dy1(0) == 0)

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

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.

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

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

% fourier variable.

Flaplace = laplace(F)

ilaplace(Fout) % Result

fourier( cos(3*t) )

ifourier( pi*(dirac(w-7)+dirac(w+7)) ) % By default, this is in complex

% exponential format

% sines and cosines

Math Toolbox Software\Using Graphics.

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

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

ezplot(sin(t))

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

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;

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

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)

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

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.

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)

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

%% Examples using polyfit and polyval

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

yVals = -3*tVals-4;

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

pLin = polyfit(tVals,yValsNoise,1); % 1st order (linear)

pQuad = polyfit(tVals,yValsNoise,10); % 10th order (overfitted)

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

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

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.

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.

%% Working with ODE45

% 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(t,y,'bo-')

grid on, xlabel('Time'), ylabel('y(t)')

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

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.

%% ODE45 and Piecewise Differential Equations

% Here, the m-file is ex5 4.m. Notice the inclusion of the @ symbol.

[t y] = ode45(@ex5 5, [0 60], 0);

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.

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

%% ODE45 and Systems of Differential Equations

% Here, the m-file is ex5 6.m and describes a Lorentz attractor.

[t x] = ode45(@ex5 6, [0 10], [15 10 10]);

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

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(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.

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

%% Generate some data with a fixed sampling rate

sampRate = 10e3; dT = 1/sampRate;

% different magnitudes

f1 = 35; f2 = 65; f3 = 100; f4 = 125;

mag1 = 0.25; mag2 = 0.3; mag3 = 0.2; mag4 = 0.2;

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

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

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

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

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.

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

- 7 Electre MethodUploaded byAllien Wang
- Mathematics_Value Based Question_12Uploaded byOP Gupta
- Thaddeus H.black DerivationsUploaded byMichael B. Vincent
- Octave-Matlab-TutorialUploaded byErvita Risnandari
- MATLAB Basic Commands.pdfUploaded byrathnam.pm
- Cp Lab ManualUploaded bypatrocs
- part 1Uploaded byBrhane W Ygzaw
- Subplot MatlabUploaded by_Leonel_
- maltab graphicsUploaded byOloyede Isiaka
- Intro to MatlabUploaded byAnkit Verma
- CBSE 11-12 MAths SyllabusUploaded byRahul Thakurta
- DirectFileTopicDownload (11).pdfUploaded byKarthik V Kalyani
- IITJEEPCMUploaded byvineetthesuperman
- datasheet mat lab.pdfUploaded byOscar Franco M
- MathsI sallybus.pdfUploaded byfahimhub
- Analisis Trial Mm 2015 (p2)Uploaded byFarah Wahida Isa
- matlab1Uploaded byRishabhMundhada
- Notice_Engl_NDA_NA _I_ Exam_ 2017_0.pdfUploaded bymanoj yadav
- MATLABsumtumUploaded byveenadivyakish
- lab02Uploaded byhideto290
- KG_ 2019 _B04_01_EnUploaded byMikko Loren
- 12 Maths CBSE Exam Papers 2017 Comptt Delhi Set 2Uploaded byRinki Bharti
- Jee Advanced SyllabusUploaded byBalaji Yaswanth Vankala
- Matrix OperationsUploaded byEsmir Haskic
- [Scot._1970_Symposium_on_the_Theory_of_Numerical_A(BookZZ.org).pdfUploaded byAshiqueHussain
- CHAPTER02-Review Topics [Compatibility Mode].pdfUploaded byamin
- Implementing Linear Algebraalgorithms for Dense MatricesUploaded byFilipe Amaro
- ManUploaded byEmmanuel AeroEng Zingapeta
- StrassenUploaded bylinchi
- Matrices & Determinants.pdfUploaded bySandeep vishwakarma

- Symbolic Math Toolbox 5 User's Guide.pdfUploaded byDennis Vilaña
- cnc mathUploaded bycaptain_jack_zzz609
- Mowete 1Uploaded bysullywas
- TEST ON TRIGONOMETRY ON IITJEE LEVELUploaded byHimansu Mookherjee
- Calcqq.forUploaded bykgrhoads
- 4rth Semester Matlab Assignment Solved 70 QuestionUploaded byUzair Ashraf
- Obstacle in Chain Survey and the Solution.Uploaded bysuria
- Calculate Distance Bearing - Movable Type ScriptsUploaded byNuru J. Haule
- matlab.docxUploaded byErik Perez
- Iit-jee Mock 1_paper iUploaded byAbhishekSinghGaur
- Unit-4-balancing-of-ROTATING-MASSES.pdfUploaded byRichard Mortimer
- Plane Wave Propagation and ReflectionUploaded byAaron Merrill
- Indeterminate Forms and L.Hospitals RuleUploaded byAmmar Zaky
- FCI 2012 SyllabusUploaded byDuvvuri Purnima
- math812grsmUploaded bygeswin ching
- A Unique Solution for Flight Body Angular HistoriesUploaded byyarara
- Useful C Library FunctionUploaded byravi
- PF_13_14_T1_Project1_030713Uploaded byShalini Kalyani
- MAS430_Homework_1.pdfUploaded byDinh Quy Duong
- Cables ConcUploaded byRyan
- 5.1Uploaded byjorge_2010
- Chapter 4 Solutions MCV4UUploaded byVoormila Nithiananda
- AJC H2Maths 2012Prelim P1 QuestionUploaded byofji4o
- Allen-RMO-2018_Solutions.pdfUploaded bynavin gupta
- 0606_s13_qp_21Uploaded byFuadi Anwar Wirawan
- A Level l3 Mathematics SpecificationUploaded byMOISES ALCOBIA
- 2017-04-24 Basic Trigonometric EquationsUploaded bysamjshah
- Solution of Engineering MatgematicsUploaded byEng W Ea
- Thesis: The Use of Magic Hexagon in Trigonometric IdentitiesUploaded byKim Gabrielle Del Puerto
- List of Important Mathematicians - The Story of MathematicsUploaded bykale sanjay