non-accredited matlab tutorial sessions for beginner ... · 9/2/2010  · 05.10.2011 5 using matlab...

76
05.10.2011 1 Matlab Training Session 1: Introduction to Matlab for Graduate Research Non-Accredited Matlab Tutorial Sessions for beginner to intermediate level users Purpose: To teach essential skills necessary for the acquisition, analysis, and graphical display of research data Non-Accredited Matlab Tutorial Sessions for beginner to intermediate level users Purpose: To teach essential skills necessary for the acquisition, analysis, and graphical display of research data Promote Self Sufficiency and Independence Outline This presentation will independently cover a new and progressively more advanced Matlab topic 1. Introduction to Matlab and its Interface 2. Fundamentals (Operators) 3. Fundamentals (Flow) 4. Importing Data 5. Functions and M-Files 6. Plotting (2D and 3D) 7. Statistical Tools in Matlab 8. Analysis and Data Structures An Introduction to Matlab and its Interface A. Why Matlab? Some Common Uses for Matlab in Research An Introduction to Matlab and its Interface A. Why Matlab? Some Common Uses for Matlab in Research B. Understanding the Matlab Environment: Navigating the Matlab Desktop Commonly used Toolbox Components Executing Commands Help and Documentation

Upload: others

Post on 15-Jul-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

1

Matlab Training Session 1:Introduction to Matlab for Graduate

Research

Non-Accredited Matlab Tutorial Sessions for beginner

to intermediate level users

Purpose: To teach essential skills necessary for the

acquisition, analysis, and graphical display of

research data

Non-Accredited Matlab Tutorial Sessions for beginner

to intermediate level users

Purpose: To teach essential skills necessary for the

acquisition, analysis, and graphical display of

research data

Promote Self Sufficiency and Independence

Outline

This presentation will independently cover a new and

progressively more advanced Matlab topic

1. Introduction to Matlab and its Interface

2. Fundamentals (Operators)

3. Fundamentals (Flow)

4. Importing Data

5. Functions and M-Files

6. Plotting (2D and 3D)

7. Statistical Tools in Matlab

8. Analysis and Data Structures

An Introduction to Matlab and its Interface

A. Why Matlab?

Some Common Uses for Matlab in Research

An Introduction to Matlab and its Interface

A. Why Matlab?Some Common Uses for Matlab in Research

B. Understanding the Matlab Environment:• Navigating the Matlab Desktop

• Commonly used Toolbox Components

• Executing Commands

• Help and Documentation

Page 2: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

2

An Introduction to Matlab and its Interface

A. Why Matlab?Some Common Uses for Matlab in Research

B. Understanding the Matlab Environment:• Navigating the Matlab Desktop

• Commonly used Toolbox Components

• Executing Commands

• Help and Documentation

C. Using Matlab:

• Matrices, Scalars and Arrays

• Useful Commands

• Searching and Indexing

• Saving and Reloading Work

An Introduction to Matlab and its Interface

A. Why Matlab?Some Common Uses for Matlab in Research

B. Understanding the Matlab Environment:• Navigating the Matlab Desktop

• Commonly used Toolbox Components

• Executing Commands

• Help and Documentation

C. Using Matlab:

• Matrices, Scalars and Arrays

• Useful Commands

• Searching and Indexing

• Saving and Reloading Work

D. Exercises

Why Matlab?

• Matrix Labratory

• Created in late 1970’s

• Intended for used in courses in matrix theory,

linear algebra and numerical analysis

Why Matlab?

• Matrix Labratory

• Created in late 1970’s

• Intended for used in courses in matrix theory,

linear algebra and numerical analysis

• Currently has grown into an interactive system

and high level programming language for general

scientific and technical computation

Why Matlab?

Common Uses for Matlab in Research

• Data Acquisition

• Multi-platform, Multi Format data importing

• Analysis Tools (Existing,Custom)

• Statistics

• Graphing

• Modeling

Why Matlab?

Data Acquisition

• A framework for bringing live, measured data into

MATLAB using PC-compatible, plug-in data

acquisition hardware

Page 3: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

3

Why Matlab?Multi-platform, Multi Format data importing

• Data can be loaded into Matlab from almost any

format and platform

• Binary data files (eg. REX, PLEXON etc.)

• Ascii Text (eg. Eyelink I, II)

• Analog/Digital Data files

PC

UNIX100101010

Subject 1 143

Subject 2 982

Subject 3 87 C

Why Matlab?Analysis Tools

• A Considerable library of analysis tools exist for

data analysis

• Provides a framework for the design, creation,

and implementation of any custom analysis tool

imaginable

Why Matlab?

Statistical Analysis

• A considerable variety of statistical tests available including:

– TTEST

– Mann-Whitney Test

– Rank Sum Test

– ANOVAs

– Linear Regressions

– Curve Fitting

Why Matlab?

Graphing

• A Comprehensive array of plotting options

available from 2 to 4 dimensions

• Full control of formatting, axes, and other visual

representational elements

Why Matlab?

Modeling

• Models of complex dynamic system interactions

can be designed to test experimental data

Understanding the Matlab

Environment:

Navigating the Matlab Desktop

Page 4: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

4

Understanding the Matlab

Environment:

Navigating the Matlab Desktop

Commonly Used Toolboxes

Understanding the Matlab

Environment:

Navigating the Matlab Desktop

Commonly Used Toolboxes

Executing CommandsBasic Calculation Operators:

+ Addition

- Subtraction

* Multiplication

/ Division

^ Exponentiation

Solving equations using variablesession language

• Expressions typed by the user are interpreted and evaluated by

the Matlab system

• Variables are names used to store values

• Variable names allow stored values to be retrieved for

calculations or permanently saved

Variable = Expression

Or

Expression

**Variable Names are Case Sensitive!

Using Matlab

Solving equations using variablesn language

• Expressions typed by the user are interpreted and evaluated by

the Matlab system

• Variables are names used to store values

• Variable names allow stored values to be retrieved for

calculations or permanently saved

Variable = Expression

Or

Expression

**Variable Names are Case Sensitive!

Using Matlab

>> x = 6

x = 6

>> y = 2

y = 2

>> x + y

Ans = 8

>> x * y

Ans = 12

>> x / y

Ans = 3

>> x ^ y

Ans = 36

Using Matlab

Working with Matrices

• Matlab works with essentially only one kind of object, a

rectangular numerical matrix

• A matrix is a collection of numerical values that are organized

into a specific configuration of rows and columns.

• The number of rows and columns can be any number

Example

3 rows and 4 columns define a 3 x 4 matrix having 12 elements

Using Matlab

Working with Matrices

• Matlab works with essentially only one kind of object, a

rectangular numerical matrix

• A matrix is a collection of numerical values that are organized

into a specific configuration of rows and columns.

• The number of rows and columns can be any number

Example

3 rows and 4 columns define a 3 x 4 matrix having 12 elements

• A scalar is a single number and is represented by a 1 x 1 matrix

in matlab.

• A vector is a one dimensional array of numbers and is

represented by an n x 1 column vector or a 1 x n row vector of n

elements

Page 5: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

5

Using Matlab

Working with Matrices

c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix

Using Matlab

Working with Matrices

c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix

x = [ 3.5, 33.22, 24.5 ] x is a row vector or a 1 x 3 matrix

Using Matlab

Working with Matrices

c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix

x = [ 3.5, 33.22, 24.5 ] x is a row vector or a 1 x 3 matrix

x1 = [ 2

5

3

-1] x1 is column vector or a 4 x 1 matrix

Using Matlab

Working with Matrices

c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix

x = [ 3.5, 33.22, 24.5 ] x is a row vector or a 1 x 3 matrix

x1 = [ 2

5

3

-1] x1 is column vector or a 4 x 1 matrix

A = [ 1 2 4

2 -2 2

0 3 5

5 4 9 ] A is a 4 x 3 matrix

Using Matlab

Working with Matrices

• Spaces, commas, and semicolons are used to separate elements

of a matrix

Using Matlab

Working with Matrices

• Spaces, commas, and semicolons are used to separate elements

of a matrix

• Spaces or commas separate elements of a row

[1 2 3 4] or [1,2,3,4]

Page 6: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

6

Using Matlab

Working with Matrices

• Spaces, commas, and semicolons are used to separate elements

of a matrix

• Spaces or commas separate elements of a row

[1 2 3 4] or [1,2,3,4]

• Semicolons separate columns

[1,2,3,4;5,6,7,8;9,8,7,6] = [1 2 3 4

5 6 7 8

9 8 7 6]

Using Matlab

Indexing Matrices

• A m x n matrix is defined by the number of m rows and number

of n columns

• An individual element of a matrix can be specified with the notation An individual element of a matrix can be specified with the notation An individual element of a matrix can be specified with the notation An individual element of a matrix can be specified with the notation A(i,j) or Ai,j for the generalized element, or by A(4,1)=5 for a specific A(i,j) or Ai,j for the generalized element, or by A(4,1)=5 for a specific A(i,j) or Ai,j for the generalized element, or by A(4,1)=5 for a specific A(i,j) or Ai,j for the generalized element, or by A(4,1)=5 for a specific element.element.element.element.

Using Matlab

Indexing Matrices

• A m x n matrix is defined by the number of m rows and number

of n columns

• An individual element of a matrix can be specified with the notation An individual element of a matrix can be specified with the notation An individual element of a matrix can be specified with the notation An individual element of a matrix can be specified with the notation A(i,j) or Ai,j for the generalized element, or by A(4,1)=5 for a specific A(i,j) or Ai,j for the generalized element, or by A(4,1)=5 for a specific A(i,j) or Ai,j for the generalized element, or by A(4,1)=5 for a specific A(i,j) or Ai,j for the generalized element, or by A(4,1)=5 for a specific element.element.element.element.

Example:

>> A = [1 2 4 5;6 3 8 2] A is a 4 x 2 matrix

>> A(1,2)

Ans 6

• The colon operator can be used to index a range of elements

>> A(1:3,2)

Ans 1 2 4

Using Matlab

Indexing Matrices

• Specific elements of any matrix can be overwritten using the

matrix index

Example:

A = [1 2 4 5

6 3 8 2]

>> A(1,2) = 9

Ans

A = [1 2 4 5

9 3 8 2]

Using Matlab

Matrix Shortcuts

• The ones and zeros functions can be used to create any m x n

matrices composed entirely of ones or zeros

Example

a = ones(2,3)

a = [1 1

1 1

1 1]

b = zeros(1,5)

b = [0 0 0 0 0]

Using MatlabData Types and Formats

• The semicolon operator determines whether the result of an

expression is displayed

• whowhowhowho lists all of the variables in your matlab workspacelists all of the variables in your matlab workspacelists all of the variables in your matlab workspacelists all of the variables in your matlab workspace

• whos list the variables and describes their matrix size

Page 7: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

7

Using Matlab

Saving your WorkTo save data to a *.mat file:

Typing ‘save filename’ at the >> prompt and the file

‘filename.mat’ will be saved to the working directory

Select Save from the file pull down menu

To reload a *.mat file

1. Type ‘load filename’ at the >> prompt to load

‘filename.mat’

(ensure the filename is located in the current working

directory)

2. Select Open from the file pull down menu and

manually find the datafile

Getting HelpHelp and Documentation

Digital 1. Updated online help from the Matlab Mathworks website:

http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.html

3. Matlab command prompt function lookup

4. Built in Demo’s

5. Websites

Hard Copy3. Books, Guides, Reference

The Student Edition of Matlab pub. Mathworks Inc.

Exercises

Enter the following Matrices in matlab using spaces,

commas, and semicolons to separate rows and

columns:

7231

9175

6211

[ ]553878122641

160

16

22

4

A = B =

C =

19246525

12100

2162855

42166418

D =

[ ]65D =

E = a 5 x 9 matrix of 1’s

Exercises

Use the who and whos functions to confirm all of the

variables and matrices in the work space are

present and correct

7231

9175

6211

[ ]553878122641

160

16

22

4

A = B =

C =

19246525

12100

2162855

42166418

D =

[ ]65D =

E = a 5 x 9 matrix of 1’s

Exercises

Change the following elements in each matrix:

7231

9175

661

[ ]553878122641

160

16

22

4

A = B =

C =

19246525

12100

2162855

42166418

D =

[ ]65D =

E = a 5 x 9 matrix of 1’s

76

76

76

76

76

0

0

0

Matlab Training Session 2:

Matrix Operations and Relational

Operators

Page 8: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

8

Fundamentals of Matlab 1

A.Review

B. Matrix Operations:

• The empty matrix

• Creating multi-dimensional matrices

• Manipulating Matrices

• Matrix Operations

C. Operators

• Relational Operators

Review

Working with Matrices

c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix

x = [ 3.5, 33.22, 24.5 ] x is a row vector or a 1 x 3 matrix

x1 = [ 2

5

3

-1] x1 is column vector or a 4 x 1 matrix

A = [ 1 2 4

2 -2 2

0 3 5

5 4 9 ] A is a 4 x 3 matrix

Indexing Matrices

• A m x n matrix is defined by the number of m rows and number

of n columns

• An individual element of a matrix can be specified with the notation An individual element of a matrix can be specified with the notation An individual element of a matrix can be specified with the notation An individual element of a matrix can be specified with the notation A(i,j) or Ai,j for the generalized element, or by A(4,1)=5 for a specific A(i,j) or Ai,j for the generalized element, or by A(4,1)=5 for a specific A(i,j) or Ai,j for the generalized element, or by A(4,1)=5 for a specific A(i,j) or Ai,j for the generalized element, or by A(4,1)=5 for a specific element.element.element.element.

Example:

>> A = [1 2 4 5;6 3 8 2] A is a 4 x 2 matrix

>> A(1,2)

Ans 6

Review

Indexing Matrices

• Specific elements of any matrix can be overwritten using the

matrix index

Example:

A = [1 2 4 5

6 3 8 2]

>> A(1,2) = 9

Ans

A = [1 2 4 5

9 3 8 2]

Review

Indexing MatricesA = [1 2 4 5

6 3 8 2]

• The colon operator can be used to index a range of elements

>> A(1:3,2)

Ans 1 2 4

Review

Indexing MatricesA = [1 2 4 5

6 3 8 2]

• The colon operator can index all rows or columns without setting

an explicit range

>> A(:,3)

Ans 4 8

>> A(2,:)

Ans 6 3 8 2

Matrix Indexing Cont..

Page 9: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

9

B. Matrix Operations

Indexing Matrices• An empty or null matrix can be created using square brackets

>> A = [ ]

** TIP: The size and length functions can quickly return the number

of elements and dimensions of a matrix variable

Matrix Operations

Indexing MatricesA = [1 2 4 5

6 3 8 2]

• The colon operator can can be used to remove entire rows or

columns

>> A(:,3) = [ ]

A = [1 2 5

6 3 2]

>> A(2,:) = [ ]

A = [1 2 5]

Matrix Operations

A = [1 2 4 5 B = [5 3 7 9

6 3 8 2] 1 9 9 8]

• Multidimensional matrices can be created by concatenating 2-D

matrices together

• The cat function concatenates matrices of compatible

dimensions together:

Usage: cat(dimensions, Matrix1, Matrix2)

N – Dimensional Matrices

ExamplesA = [1 2 4 5 B = [5 3 7 9

6 3 8 2] 1 9 9 8]

>> C = cat(3,[1,2,4,5;6,3,8,2],[5,3,7,9;1,9,9,8])

>> C = cat(3,A,B)

N – Dimensional Matrices

Scalar Operations• Scalar (single value) calculations can be can performed on

matrices and arrays

Basic Calculation Operators

+ Addition

- Subtraction

* Multiplication

/ Division

^ Exponentiation

Matrix Operations

Page 10: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

10

Scalar Operations• Scalar (single value) calculations can be performed on matrices

and arrays

A = [1 2 4 5 B = [1 C = 5

6 3 8 2] 7

3

3]

Try:

A + 10

A * 5

B / 2

A^C

Matrix Operations

Scalar Operations• Scalar (single value) calculations can be performed on matrices

and arrays

A = [1 2 4 5 B = [1 C = 5

6 3 8 2] 7

3

3]

Try:

A + 10

A * 5

B / 2

A^C What is happening here?

Matrix Operations

Matrix Operations• Matrix to matrix calculations can be performed on matrices and

arrays

Addition and Subtraction• Matrix dimensions must be the same or the added/subtracted

value must be scalar

A = [1 2 4 5 B = [1 C = 5 D = [2 4 6 8

6 3 8 2] 7 1 3 5 7]

3

3]

Try:

>>A + B >>A + C >>A + D

Matrix Operations

Matrix Multiplication

• Built in matrix multiplication in Matlab is either:

1. Algebraic dot product

2. Element by element multiplication

Matrix Operations

The Dot Product

• The dot product for two matrices A and B is defined whenever the

number of columns of A are equal to the number of rows of b

• A(x1,y1) * B(x2,y2)

Matrix Operations

The Dot Product

• The dot product for two matrices A and B is defined whenever the

number of columns of A are equal to the number of rows of b

• A(x1,y1) * B(x2,y2)

Matrix Operations

Page 11: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

11

The Dot Product

• The dot product for two matrices A and B is defined whenever the

number of columns of A are equal to the number of rows of b

• A(x1,y1) * B(x2,y2)

Matrix Operations

The Dot Product

• The dot product for two matrices A and B is defined whenever the

number of columns of A are equal to the number of rows of b

• A(x1,y1) * B(x2,y2) = C(x1,y2)

Matrix Operations

The Dot Product

• A(x1,y1) * B(x2,y2) = C(x1,y2)

A = [1 2 B = [1 D = [2 2 E = [2 4 3 6]

6 3] 7 2 2]

3

3]

Try:

>>A * D

>>B * E

>>A * B

Matrix Operations

Element by Element Multiplication• Element by element multiplication of matrices is performed with

the .* operator

• Matrices must have identical dimensions

A = [1 2 B = [1 D = [2 2 E = [2 4 3 6]

6 3 ] 7 2 2 ]

3

3]

>>A .* D

Ans = [ 2 4

12 6]

Matrix Operations

Matrix Division

• Built in matrix division in Matlab is either:

1. Left or right matrix division

2. Element by element division

Matrix Operations

Left and Right Division

• Left and Right division utilizes the / and \ operators

• Left (\) division:

X = A\B is a solution to A*X = B

• Right (/) division:

X = B/A is a solution to X*A = B

• Left division requires A and B have the same number of rows

• Right division requires A and B have the same number of

columns

Matrix Operations

Page 12: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

12

Element by Element Division• Element by element division of matrices is performed with the ./

operator

• Matrices must have identical dimensions

A = [1 2 4 5 B = [1 D = [2 2 2 2 E = [2 4 3 6]

6 3 8 2] 7 2 2 2 2]

3

3]

>>A ./ D

Ans = [ 0.5000 1.0000 2.0000 2.5000

3.0000 1.5000 4.0000 1.0000 ]

Matrix Operations

Element by Element Division

• Any division by zero will be returned as a NAN in matlab (not a

number)

• Any subsequent operation with a NAN value will return NAN

Matrix Operations

Matrix Exponents

• Built in matrix Exponentiation in Matlab is either:

1. A series of Algebraic dot products

2. Element by element exponentiation

Examples:

• A^2 = A * A (Matrix must be square)

• A.^2 = A .* A

Matrix Operations

Shortcut: Transposing Matrices• The transpose of a matrix is the matrix formed by interchanging

the rows and columns of a given matrix

A = [1 2 4 5 B = [1

6 3 8 2] 7

3

3]

>> transpose(A) >> B’

A = [1 6 B = [1 7 3 3]

2 3

4 8

5 2]

Matrix Operations

Other handy built in matrix functions Include:

inv() Matrix inverse

det() Matrix determinant

poly() Characteristic Polynomial

kron() Kronecker tensor product

Matrix Operations

C. Relational Operators

Page 13: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

13

• Relational operators are used to compare two scaler values or

matrices of equal dimensions

Relational Operators

< less than

<= less than or equal to

> Greater than

>= Greater than or equal to

== equal

~= not equal

Relational Operators

• Comparison occurs between pairs of corresponding elements

• A 1 or 0 is returned for each comparison indicating TRUE or

FALSE

• Matrix dimensions must be equal!

>> 5 == 5

Ans 1

>> 20 >= 15

Ans 1

Relational Operators

A = [1 2 4 5 B = 7 C = [2 2 2 2

6 3 8 2] 2 2 2 2]

Try:

>>A > B

>> A < C

Relational Operators

The Find Function• The ‘find’ function is extremely helpful with relational operators

for finding all matrix elements that fit some criteria

A = [1 2 4 5 B = 7 C = [2 2 2 2 D = [0 2 0 5 0 2]

6 3 8 2] 2 2 2 2]

• The positions of all elements that fit the given criteria are

returned

>> find(D > 0)

• The resultant positions can be used as indexes to change these

elements

>> D(find(D>0)) = 10 D = [10 2 10 5 10 2]

Relational Operators

The Find Function

A = [1 2 4 5 B = 7 C = [2 2 2 2 D = [0 2 0 5 0 2]

6 3 8 2] 2 2 2 2]

• The ‘find’ function can also return the row and column indexes of

of matching elements by specifying row and column arguments

>> [x,y] = find(A == 5)

• The matching elements will be indexed by (x1,y1), (x2,y2), R

>> A(x,y) = 10

A = [ 1 2 4 10

6 3 8 2 ]

Relational Operators

Matlab Training Session 3:

Control and Flow

Page 14: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

14

Fundamentals of Matlab 3

A. Review

B. Multiple Command Execution• Breaking up long command instructions

• Entering multiple commands for execution

• Scripts

C. Control and Flow

• Logical Operators

• Condition Statements

• Loops

N – Dimensional matrices

A = [1 2 4 5 B = [5 3 7 9

6 3 8 2] 1 9 9 8]

• Multidimensional matrices can be created by concatenating 2-D

matrices together

• The cat function concatenates matrices of compatible

dimensions together:

Usage: cat(dimensions, Matrix1, Matrix2)

Review

Scalar Operations• Scalar (single value) calculations can be performed on matrices

and arrays

A = [1 2 4 5 B = [1 C = 5

6 3 8 2] 7

3

3]

Try:

A + 10

A * 5

B / 2

Review

Matrix Operations• Matrix to matrix calculations can be performed on matrices and

arrays

Addition and Subtraction• Matrix dimensions must be the same or the added/subtracted

value must be scalar

A = [1 2 4 5 B = [1 C = 5 D = [2 4 6 8

6 3 8 2] 7 1 3 5 7]

3

3]

Try:

>>A + B >>A + C >>A + D

Review

Matrix Multiplication

• Built in matrix multiplication in Matlab is either:

1. Algebraic dot product

2. Element by element multiplication

Review

The Dot Product

• A(x1,y1) * B(x2,y2) = C(x1,y2)

Element by Element Multiplication• Element by element multiplication of matrices is performed with

the .* operator

• Matrices must have identical dimensions

Review

Page 15: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

15

Matrix Division

• Built in matrix division in Matlab is either:

1. Left or right matrix division

2. Element by element division

Review

Left and Right Division

• Left and Right division utilizes the / and \ operators

• Left (\) division:

X = A\B is a solution to A*X = B

• Right (/) division:

X = B/A is a solution to X*A = B

• Left division requires A and B have the same number of rows

• Right division requires A and B have the same number of

columns

Review

Element by Element Division• Element by element division of matrices is performed with the ./

operator

• Matrices must have identical dimensions

Review

Matrix Exponents

• Built in matrix Exponentiation in Matlab is either:

1. A series of Algebraic dot products

2. Element by element exponentiation

Examples:

• A^2 = A * A (Matrix must be square)

• A.^2 = A .* A

Review

Relational Operators

• Relational operators are used to compare two scaler values or

matrices of equal dimensions

Relational Operators

< less than

<= less than or equal to

> Greater than

>= Greater than or equal to

== equal

~= not equal

Review

Relational Operators

• Comparison occurs between pairs of corresponding elements

• A 1 or 0 is returned for each comparison indicating TRUE or

FALSE

• Matrix dimensions must be equal!

>> 5 == 5

Ans 1

>> 20 >= 15

Ans 1

Review

Page 16: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

16

The Find Function• The ‘find’ function is extremely helpful with relational operators

for finding all matrix elements that fit some criteria

A = [1 2 4 5 B = 7 C = [2 2 2 2 D = [0 2 0 5 0 2]

6 3 8 2] 2 2 2 2]

• The positions of all elements that fit the given criteria are

returned

>> find(D > 0)

• The resultant positions can be used as indexes to change these

elements

>> D(find(D>0)) = 10 D = [10 2 10 5 10 2]

Review

The Find Function

A = [1 2 4 5 B = 7 C = [2 2 2 2 D = [0 2 0 5 0 2]

6 3 8 2] 2 2 2 2]

• The ‘find’ function can also return the row and column indexes of

of matching elements by specifying row and column arguments

>> [x,y] = find(A == 5)

• The matching elements will be indexed by (x1,y1), (x2,y2), R

>> A(x,y) = 10

A = [ 1 2 4 10

6 3 8 2 ]

Review

Embedding Functions• Functions may be embedded into other functions, i.e. the values

sent to a function can be the result from some other function

• Function embedding can be many levels deep

• Many lines of code can be condensed into one single command

A = [1 2 4 5 B = 2 C = [2 2 2 2 D = [0 2 0 3 0 2]

6 3 8 2] 2 2 2 2]

>> D(find(D>0))

Ans 2 3 2

Matrix Operations

Embedding Functions• Functions may be embedded into other functions, i.e. the values

sent to a function can be the result from some other function.

• Function embedding can be many levels deep

• Many lines of code can be condensed into one single command

A = [1 2 4 5 B = 2 C = [2 2 2 2 D = [0 2 0 3 0 2]

6 3 8 2] 2 2 2 2]

>> D(find(D>0))

Ans 2 3 2

>>D(D(find(D>0)))

Ans 2 0 0

Matrix Operations

Embedding Functions• Functions may be embedded into other functions, i.e. the values

sent to a function can be the result from some other function.

• Function embedding can be many levels deep

• Many lines of code can be condensed into one single command

A = [1 2 4 5 B = 2 C = [2 2 2 2 D = [0 2 0 3 0 2]

6 3 8 2] 2 2 2 2]

>> D(find(D>0))

Ans 2 3 2

>>D(D(find(D>0)))

Ans 2 0 0

>>A(B, D(find(D>0)) )

Ans 3 8 3

Matrix Operations

B. Multiple Command

Execution

Page 17: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

17

Entering Long Lines of Code• If a matlab command contains many calculations, embedded functions

or long variable names, it may be necessary to split the command onto

multiple lines so that it can be read more easily

• The ‘R’ command tells matlab to continue the current command onto

the next line

Programming Tricks

Entering Long Lines of Code• If a matlab command contains many calculations, embedded functions

or long variable names, it may be necessary to split the command onto

multiple lines so that it can be read more easily

• The ‘R’ command tells matlab to continue the current command onto

the next line

>> long_variable_name1 + long_variable_name2 + mean(long_variable_name3)

Programming Tricks

Entering Long Lines of Code• If a matlab command contains many calculations, embedded functions

or long variable names, it may be necessary to split the command onto

multiple lines so that it can be read more easily

• The ‘R’ command tells matlab to continue the current command onto

the next line

>> long_variable_name1 + long_variable_name2 + mean(long_variable_name3)

>> long_variable_name1 + long_variable_name2 + R

mean(long_variable_name3)

Programming Tricks

Entering Multiple Lines Without Running Them• To enter multiple lines before running any of them, use Shift+Enter

or Shift+Return.

• The cursor moves down to the next line, where the next line can be

written.

• to run all of the lines press Enter or Return .

• This allows the list of commands to be checked and edited before

they are evaluated by matlab.

Programming Tricks

Entering Multiple Lines Without Running Them• Matlab can execute sequences of commands stored in files

• Files that contain matlab commands have the extension ‘*.m’

• *.m files are written and saved in the built in matlab m-file editor

• M-files are executed from the M-file editor or the command prompt

• M-files can call other M-files

**The location path of the M-file must be set in matlab

Matlab Scripts

Advantages of M-files

• Easy editing and saving of work

• Undo changes

• Readability/Portability - non executable comments can be

added using the ‘%’ symbol to make make commands easier to

understand

• Saving M-files is far more memory efficient than saving a

workspace

Matlab Scripts

Page 18: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

18

C. Control and Flow

• Logical operators are used to compare two boolean

values

• A boolean value is a logical representation of true or

false

• Conventionally 1 and 0 are used to represent true and

false

• In matlab when boolean comparisons are made, a

value of ‘false’ or 0 represents false and any positive

integer or ‘true’ represents true

Logical Operators

Logical Operators

& AND

| OR

~ NOT

• The & (AND) operator returns TRUE only if both A,B

values are TRUE otherwise returns FALSE

& (AND) Truth Table: A B Result

1 1 1

1 0 0

0 1 0

0 0 0

Logical Operators

A & B = ?

Logical Operators

& AND

| OR

~ NOT

• The | (OR) operator returns TRUE if either A, B is

TRUE, otherwise returns FALSE

| (OR) Truth Table: A B Result

1 1 1

1 0 1

0 1 1

0 0 0

Logical Operators

A | B = ?

Logical Operators

& AND

| OR

~ NOT

• The ~ (NOT) operator reverses the boolean

representation

~ (NOT) Truth Table: A ~A B ~B

1 0 1 0

0 1 0 1

Logical Operators

~A = ?

~B = ?

Examples:

A = 0 B = false C = 1 D = 8 E = true

F = [ 0 1 0 2

0 3 0 1]

Try:

>>A & B >>A & C >>A & D >>A & E >>A & F

>>A | B >>A | C >>A | D >>A | E >>A | F

>> ~A >> ~B >> ~C >> ~D >> ~E

>> ~F >> ~A&C >> ~C & F

Logical Operators

Page 19: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

19

Examples:

A = 0 B = false C = 1 D = 8 E = true

F = [ 0 1 0 2

0 3 0 1]

>>A & B = 0 >>A & C = 0 >>A & D = 0 >>A & E = 0

>>A & F = [0 0 0 0 >>A | B = 0 >>A | C = 1

0 0 0 0] >>A | D = 1 >>A | E = 1

>>A | F = [0 1 0 1

0 1 0 1]

Logical OperatorsExamples:

A = 0 B = false C = 1 D = 8 E = true

F = [ 0 1 0 2

0 3 0 1]

>> ~A = 1 >> ~B = 1 >> ~C = 0

>> ~D = 0 >> ~E = 0

>> ~F =[1 0 1 0 >> ~A&C = 1 >> ~C & F = [0 0 0 0

1 0 1 0] 0 0 0 0]

**When performing a boolean operation with a matrix, an

element by element boolean comparison is made

Logical Operators

Order of Precedence:

• When performing multiple logical operations without

separating brackets, the ~ (NOT) operator is evaluated

first, followed by the & (AND) operator and | (OR)

operator

A&B|C = (A&B) | C

A|B&C = A | (B&C)

Logical OperatorsOrder of Precedence:

• When performing multiple logical operations without

separating brackets, the ~ (NOT) operator is evaluated

first, followed by the & (AND) operator and | (OR)

operator

A&B|C = (A&B) | C

A|B&C = A | (B&C)

A&~B|C = (A&(~B)) | C

A|~B&C = A | ((~B)&C)

Logical Operators

• Control flow capability enables matlab to function

beyond the level of a simple desk calculator

• With control flow statements, matlab can be used as a

complete high-level matrix language

• Flow control in matlab is performed with condition

statements and loops

Control and Flow

• It is often necessary to only perform matlab

operations when certain conditions are met

• Relational and Logical operators are used to define

specific conditions

• Simple flow control in matlab is performed with the ‘If’,

‘Else’, ‘Elseif’ and ‘Switch’ statements

Condition Statements

Page 20: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

20

If, Else, and Elseif

• An if statement evaluates a logical expression and evaluates a

group of commands when the logical expression is true

• The list of conditional commands are terminated by the end

statement

• If the logical expression is false, all the conditional commands

are skipped

• Execution of the script resumes after the end statement

Basic form:

if logical_expression

commands

end

Condition Statements

Example

A = 6 B = 0

if A > 6

D = [1 2 6]

A = A + 1

end

if A | B

E = mean(B)

end

Condition Statements

If, Else, and Elseif

• The else statement forces execution of the commands below the

else statement if the original logical expression evaluates to false

• Only one list of commands can be executed

Basic form:

if logical_expression

commands 1

else

commands 2

end

Condition Statements

Example

A = 6 B = 0

if A > 6

D = [1 2 6]

A = A + 1

else

D = [ 0 0 0]

A = A - 1

end

Condition Statements

if A & B

E = mean(B)

else

E = 0

end

If, Else, and Elseif

• The elseif statement forces execution of the commands below

the else statement if the original logical expression evaluates to

false

• Only one list of commands can be executed

Basic form:

if logical_expression

commands 1

elseif logical_expression_2

commands 2

elseif logical_expression_3

commands 3

end

Condition StatementsExample

A = 6 B = 0

if A > 3

D = [1 2 6]

A = A + 1

elseif A > 2

D = D + 1

A = A + 2

end

** Both the if and elseif statements are evaluated

Condition Statements

Page 21: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

21

Switch• The switch statement can act as many elseif statements

• Only the one case statement who’s value satisfies the original

expression is evaluated

Basic form:

switch expression (scalar or string)

case value 1

commands 1

case value 2

commands 2

case value n

commands n

end

Condition StatementsExample

A = 6 B = 0

switch A

case 4

D = [ 0 0 0]

A = A - 1

case 5

B = 1

case 6

D = [1 2 6]

A = A + 1

end

** Only case 6 is evaluated

Condition Statements

• Loops are an important component of flow control

that enables matlab to repeat multiple statements in

specific and controllable ways

• Simple repetition in matlab is controlled by two types

of loops:

1. For loops

2. While loops

Loops

For Loops

• The for loop executes a statement or group of

statements a predetermined number of times

Basic Form:

for index = start:increment:end

statements

end

** If ‘increment’ is not specified, an increment of 1 is assumed

by matlab

Loops

For Loops

Examples:

for i = 1:1:100

x(i) = 0

end

• Assigns 0 to the first 100 elements of vector x

• If x does not exist or has fewer than 100 elements,

additional space will be automatically allocated

LoopsFor Loops

• Loops can be nested in other loops

A = [ ]

for i = 1:m

for j = 1:n

A(i,j) = i + j

end

end

• Creates an m by n matrix A whose elements are the

sum of their matrix position

Loops

Page 22: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

22

While Loops

• The while loop executes a statement or group of

statements repeatedly as long as the controlling

expression is true

Basic Form:

while expression

statements

end

LoopsWhile Loops

Examples:

A = 6 B = 15

while A > 0 & B < 10

A = A + 1

B = B – 2

end

• Iteratively increase A and decrease B until the two

conditions of the while loop are met

** Be very careful to ensure that your while loop will

eventually reach its termination condition to prevent

an infinite loop

Loops

While Loops

Examples:

A = 6 B = 15

while A > 0 & B < 10

if A < 0

A = A + 1

elseif B > 10

B = B – 2

end

end

• Conditional statements can be nested for specific

internal control of variables

LoopsBreaking out of loops

• The ‘break’ command instantly terminates a for and

while loop

• When a break is encountered by matlab, execution of

the script continues outside and after the loop

Loops

Breaking out of loops

Example:

A = 6 B = 15

count = 1

while A > 0 & B < 10

A = A + 1

B = B + 2

count = count + 1

if count > 100

break

end

end

• Break out of the loop after 100 repetitions if the while

condition has not been met

Loops

Matlab Training Session 4:

Control, Flow and Functions

Page 23: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

23

Entering Multiple Lines Without Running Them• Matlab can execute sequences of commands stored in files

• Files that contain matlab commands have the extension ‘*.m’

• *.m files are written and saved in the built in matlab m-file editor

• M-files are executed from the M-file editor or the command prompt

• M-files can call other M-files

**The location path of the M-file must be set in matlab

Matlab Scripts

Advantages of M-files

• Easy editing and saving of work

• Undo changes

• Readability/Portability - non executable comments can be

added using the ‘%’ symbol to make make commands easier to

understand

• Saving M-files is far more memory efficient than saving a

workspace

Matlab Scripts

Relational Operators

• Relational operators are used to compare two scaler values or

matrices of equal dimensions

Relational Operators

< less than

<= less than or equal to

> Greater than

>= Greater than or equal to

== equal

~= not equal

Review

• It is often necessary to only perform matlab

operations when certain conditions are met

• Relational and Logical operators are used to define

specific conditions

• Simple flow control in matlab is performed with the ‘If’,

‘Else’, ‘Elseif’ and ‘Switch’ statements

Condition Statements

If, Else, and Elseif

• An if statement evaluates a logical expression and evaluates a

group of commands when the logical expression is true

• The list of conditional commands are terminated by the end

statement

• If the logical expression is false, all the conditional commands

are skipped

• Execution of the script resumes after the end statement

Basic form:

if logical_expression

commands

end

Condition StatementsIf, Else, and Elseif

• The elseif statement forces execution of the commands below

the else statement if the original logical expression evaluates to

false

• Only one list of commands can be executed

Basic form:

if logical_expression

commands 1

elseif logical_expression_2

commands 2

elseif logical_expression_3

commands 3

end

Condition Statements

Page 24: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

24

• Loops are an important component of flow control

that enables matlab to repeat multiple statements in

specific and controllable ways

• Simple repetition in matlab is controlled by two types

of loops:

1. For loops

2. While loops

Loops

For Loops

• The for loop executes a statement or group of

statements a predetermined number of times

Basic Form:

for index = start:increment:end

statements

end

** If ‘increment’ is not specified, an increment of 1 is assumed

by matlab

Loops

While Loops

• The while loop executes a statement or group of

statements repeatedly as long as the controlling

expression is true

Basic Form:

while expression

statements

end

Loops Functions

• Building blocks of programming

• Allow code to be generic and reusable

• Design from top down but build from bottom up

• Take a set of inputs, perform a series of

manipulations and return an output

Functions in Matlab

• In Matlab, each function is a .m file

– It is good protocol to name your .m file the same as

your function name, i.e. funcname.m

• function outargs=funcname(inargs);

Function outputinput

Simple Example

• Find the cube of a number -> (x3)

• Type the code below into an .m file and save it as cube.m

• Set the Matlab directory appropriately

• In Matlab window, type cube(3), is the result correct?

• Now you have a reusable function that can calculate the cube of any number

function [y] = cube(x)

y = x*x*x;

>> cube(3)

Ans = 125

>> cube 1.75

Ans = 5.3594

Page 25: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

25

Add Some Help

• Find the cube of a number -> (x3)

• Add commented text between the funciton

declaration and the first line of code

• Now type help cube in Matlab window

function [y] = cube(x)

% Put some text here

y = x*x*x;

>> help cube

Put some text here

Find the cube of two numbers

• Any numbers of inputs and outputs can be

handled in a function

• For a simple example, extend the cube

function to accept two inputs and find the

cube of each

function [y1, y2] = cube(x1, x2)

% Put some text here

y1 = x1*x1*x1;

y2 = x2*x2*x2

>> cube(2,3)

Ans = 4 ???

>> [a b] = cube(2,3)

a = 8

b = 27

nargin

• Matlab will accept a function call with any

number of inputs and outputs

• nargin can be used to find out how many

inputs the user has provided

– It is automatically passed with the function

function [y1, y2] = cube(x1, x2)

If nargin == 1

y1 = x1*x1*x1;

y2 = Nan;

elseif nargin == 2

y1 = x1*x1*x1;

y2 = x2*x2*x2;

end

>> cube(2,3)

Ans = 4

>> [a b] = cube(2,3)

a = 8

b = 27

return

• return terminates computation of the

function and returns whatever is calculated

thus far

function [y1, y2] = cube(x1, x2)

If nargin == 1

y1 = x1*x1*x1;

y2 = Nan;

return

endy1 = x1*x1*x1;

y2 = x2*x2*x2;

>> cube(2,3)

Ans = 4

>> [a b] = cube(2,3)

a = 8

b = 27

Find the Cube of Any Number of

Numbers

• Any ideas on how to accomplish this?

• Lets further extend the function to cube a

vector of numbers

• Before we thought of the variables as

scalars, now rethink the power of vectors

function [y] = cube(x)

% Put some text here

y = x.^3;

>> cube(2)

Ans = 8

>> cube([2 3])

Ans = [8 27]

Mini-Project

• Raising any number of numbers to the nth power

• Inputs:– A vector of numbers to be raised (N1CNm)

– A vector of powers (P1CPm)

• Outputs:– A vector of raised values (N1P1 C NmPm)

– An error flag: 1 if error in calculation, 0 if successful

• Caveats:– If only one input is provided, the function should square each

entry, so output = (N12CNm2) and error flag is 0

– If the length of N and P are not the same, this is an error, return anything in the output vector and a 1 in the error flag

• Make sure to comment and document the function

Page 26: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

26

Mini-Project

• Lets combine what we have learned thus

far in the course

– Loops, If Statements, Functions

– Basic Matlab Operators

• Should finish this in class today

• If you get through this then you are doing

well

Mini-Project

• Plan before you code

• Remember that xn=x*x*x*x C *x (n times)

• Ask questions and take your time

Solution function [y, e] = raise(x,n)

y = ones(1,length(x));

if nargin == 1

[y e] = raise(x,2*ones(1,length(x)));

return

elseif nargin == 2

if(length(x)~=length(n))

y = NaN;

e = 1;

return

end

for(i=1:length(x))

for(j=1:n(i))

y(i) = y(i)*x(i);

end

end

e = 0;

return

end

Matlab Training Session 5:

Importing Data

Importing Data

A. Review

B. Simple Import

C. Handling Files

D. Mini-Project

Functions in Matlab

• In Matlab, each function is a .m file

– It is good protocol to name your .m file the same as

your function name, i.e. funcname.m

• function outargs=funcname(inargs);

Function outputinput

Page 27: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

27

Mini-Project

• Raising any number of numbers to the nth power

• Inputs:– A vector of numbers to be raised (N1CNm)

– A vector of powers (P1CPm)

• Outputs:– A vector of raised values (N1P1 C NmPm)

– An error flag: 1 if error in calculation, 0 if successful

• Caveats:– If only one input is provided, the function should square each

entry, so output = (N12CNm2) and error flag is 0

– If the length of N and P are not the same, this is an error, return anything in the output vector and a 1 in the error flag

• Make sure to comment and document the function

SolutionComplex

function [y, e] = raise(x,n)

y = ones(1,length(x));

if nargin == 1

[y e] = raise(x,2*ones(1,length(x)));

return

elseif nargin == 2

if(length(x)~=length(n))

y = NaN;

e = 1;

return

end

for(i=1:length(x))

for(j=1:n(i))

y(i) = y(i)*x(i);

end

end

e = 0;

return

end

Simple

function [y, e] = raise(x,n)

if nargin == 1

[y e] = x.^2;

return

elseif nargin == 2

if(length(x)~=length(n))

y = NaN;

e = 1;

return

end

y = x.^n

e = 0;

end

Importing Data

• Basic issue:

– How do we get data from other sources into

Matlab so that we can play with it?

• Other Issues:

– Where do we get the data?

– What types of data can we import

• Easily or Not

load

• Command opens and imports data from a

standard ASCII file into a matlab variable

• Restrictions

– Data must be constantly sized

– Data must be ASCII

– No other characters

load

• Consider the simple file below

• Create in notepad and save as test1.txt and

text2.txt

• In matlab, set the path to the correct place (ie.

where the file is) and type load(‘test1.txt’)

• Now, type x = load(‘test1.txt’)

1 2

3 4

5 2

4 8

16 32

test1

load

• Now the file is no longer simple because not

every row has the same amount of characters

• Create in notepad and save as test2.txt and

text2.txt

• type y = load(‘test2.txt’)

– Error!

1 2

3 4

5

4 8

16 32

test2

Page 28: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

28

load

• Now type in the same thing from test1.txt into

Excel and save the workbook as test1.xls

• type y = load(‘test1.xls’)

– What happens?

• Forcing the issue with Excel data

test11 2

3 4

5 2

4 8

16 32

load

• Works for simple and unstructured code

• Powerful and easy to use but limited

• Will likely force you to manually handle

simplifying data which is prone to error

• More complex functions are more flexible

File Handling

• f* functions are associated with file opening,

reading, manipulating, writing, C

• Basic Functions of Interest for opening and

reading generic files in matlab

– fopen

– fclose

– fseek/ftell/frewind

– fscanf

– fgetl

fopen

• Opens a file object in matlab that points to the file of interest

• fid = fopen(‘filepath’)– absolute directory + filename

• If file of interest it C:\Andrew\Project_1\file.dat

• fid = fopen(‘C:\Andrew\Project_1\file.dat’)

– relative path + filename• If your matlab path is set to c:\Andrew\Project_1

• fid = fopen(‘file.dat’)

• fid is an integer that represents the file– Can open multiple files and matlab will assign unique

fids

fclose

• When you are done with a file, it is a good idea

to close it especially if you are opening many

files

• fclose(fid)

What is a File?

• A specific organization of data

• In matlab it is identified with a fid

• Location is specified with a pointer that can be

moved around

file_name

fid

Pointer

Page 29: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

29

Moving the Pointer

• We already know how to assign a fid (fopen)

• To find where the file is pointing:

– x = ftell(fid)

• To point somewhere else

– fseek(fid,offset,origin)

• Move pointer in file fid by offset relative to origin

– Origin can be beginning, current, end of file

• To point to the beginning

– frewind(fid)

Getting Data

• Why move the pointer around?

– Get somewhere in the file from where you want data

• fscanf(fid,format,size)

• Format

– You have to tell matlab the type of data it should be expecting in the text file so that it can convert it

• ‘%d’, ‘%f’, ‘%c’

• Size

– You can specify how to organize the imported data• [m,n] – import the data as m by n, n can be infinite

• Be careful because matlab will mangle your data and not tell you

Lets Try It

• Open text1.txt using the fopen command

– Remember to save the fid, we will need it

• Create a variable with the data of text1.txt

• Now create another variable y with the data of text1.txt in it by using

fscanf (do not simply copy x)

– What happens here?

– Need to set file pointer to beginning using rewind(fid)

• Now use the size option to import the data with 5 rows and 2

columns

• Try the same thing with test2.txt

– It works and fills in the blanks. This is powerful but dangerous

Getting Data

• fgetl returns the next line of the file as a

character array

• You may need to convert these to numbers

>> fid1 = fopen(‘test1.txt’);

>> a_str = fgetl(fid1)

a_str = 1 2

>> a_num = str2num(a_str)

a_num = [1 2]

Realistic File

• A realistic file of data will have header information,

labeled columns and other information embedded within

it.

– See PDXtemp.dat

• Option 1: Manually go through deleting this information

and import using load of fopen commands.

• Option 2: Have matlab delete and format available data

on the fly

Realistic File

• Powerful function textread can be used to

input almost any text file

• Handles:

– Opening the file

– Ignoring Header Information

– Accepting Column Labels

• Will work for most applications

Page 30: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

30

Summary

• Lots of options to load files

– load for basics

– fscanf for complex

– textread for most things

– xlsread for Excel worksheets

• Also saving Excel sheets as tad delimitted

Mini-Project• Using the textread function, import the full data located in

PDXtemp.dat with the stated names and correct data

types

• Take the resulting temperatures in Fahrenheit and

convert to Celsius

– Make use of Matlab help to learn about and implement the

textread function

– Deg_F = 9/5*Deg_C + 32

Getting Help

Help and Documentation

Digital 1. Accessible Help from the Matlab Start Menu

2. Updated online help from the Matlab Mathworks website:

http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.html

3. Matlab command prompt function lookup

4. Built in Demo’s

5. Websites

Hard Copy3. Books, Guides, Reference

The Student Edition of Matlab pub. Mathworks Inc.

Plotting

1. Introduction to Matlab and its Interface

2. Fundamentals (Operators)

3. Fundamentals (Flow)

4. Importing Data

5. Functions and M-Files

6. Plotting (2D and 3D)

7. Statistical Tools in Matlab

8. Analysis and Data Structures

*Classes on back to normal.

Course Website:

http://www.queensu.ca/neurosci/Matlab Training Sessions.htm

Plotting Data

A. Basics

B. Generating data

C. 2D Plots (Line, Scatter, Bar)

D. Plot Features

Page 31: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

31

Basics

• Matlab has a powerful plotting engine that can

generate a wide variety of plots.

Generating Data

• Matlab does not understand functions, it can

only use arrays of numbers.

– a=t2

– b=sin(2*pi*t)

– c=e-10*t note: matlab command is exp()

– d=cos(4*pi*t)

– e=2t3-4t2+t

• Generate it numerically over specific range

• Try and generate a-e over the interval 0:0.01:2

t=0:0.01:10; %make x vector

y=t.^2; %now we have the appropriate y

% but only over the specified range

Line/Scatter

• Simplest plot function is plot()

• Try typing plot(y)– Matlab automatically generates a figure and draws the data and

connects its lines

– Looks right, but the x axis units are incorrect

• Type plot(x,y), will look identical but have correct x-axis units

• Plot(x1,y1,s1,x2,y2,s2, C) many plots in one command

• Plot(x) where x is a matrix, will result in plotting each column as a separate trace

Line/Scatter

• Plot a and then plot b

– What do you see?

– Only b

• Matlab will replace the current plot with any new one

unless you specifically tell it not to

• To have both plots on one figure use the hold on

command

• To make multiple plots use the figure command

plot(t,a)

plot(t,b)

% Put a and b on one plot

plot(t,a);

hold on;

plot(t,b);

% Make two plots

plot(t,a);

figure;

plot(t,b);

Hold On / Hold Off

• Hold on command only needs to be issued once per

figure, thus calling hold on will result in all subsequent

plot commands going to one figure unless a new figure

command is issued or hold off is used.

plot(a);

Hold on;

plot(b);

plot(c);

Hold off;

Figure;

plot(d);

plot(a);

Hold on;

plot(b);

plot(c);

Hold off;

plot(d);

plot(a);

Hold on;

plot(b);

plot(c);

Figure;

plot(d);

Linespec• Currently, all the plots were done in the Matlab

default color C blue

• This and many other features can be changed

by selecting a different option within the plot

command

% red line

Plot(t,a,’r’);

Hold on;

% black line

Plot(t,b,’k’);

% green dots

Plot(t,c,’g.’);

% cyan x’s

Plot(t,d,’cx’)

% dashed magenta

% line with o’s

Plot(t,e,’--om’)

Page 32: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

32

Linespec• Now we have added color, line style and markers to the data

• We can also modify line width, marker edge and fill color and marker

size

% dashed magenta % line with o’s, C

Plot(t,e,’--om’, ‘LineWidth’,3,'MarkerEdgeColor',‘k‘, 'MarkerFaceColor',‘y‘, MarkerSize,9)

Labels, Title and Legend• To add labels to the x and y axes, we can use the xlabel and ylabel

commands

• To add a title, use the title command

• To add a legend, use the legend command

plot(t,a,t,b,’r’,t,c,’--om’); %generate all plots in one shot

title(‘Random Plots’)

xlabel(‘time(ms)’);

ylabel(‘f(t)’)

legend(‘Function 1’,’Function 2’,’Function 3’);

Quick Assignment 1

• Plot a as a thick black line

• Plot b as a series of red circles.

• Label each axis, add a title and a legend

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2-1

-0.5

0

0.5

1

1.5

2

2.5

3

3.5

4

Time (ms)

f(t)

Mini Assignment #1

t2

sin(2*pi*t)

Quick Assignment 1

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2-1

-0.5

0

0.5

1

1.5

2

2.5

3

3.5

4

Time (ms)

f(t)

Mini Assignment #1

t2

sin(2*pi*t)

figure

plot(t,a,'k','LineWidth',3); hold on;

plot(t,b,'ro')

xlabel('Time (ms)');

ylabel('f(t)');

legend('t^2','sin(2*pi*t)');

title('Mini Assignment #1')

Axis commands• We can alter the displayed range and other parameters of the plot by

using the axis command

– Axis([xmin xmax ymin ymax])

– Axis equal;

– Axis square;

Figure;

Plot(t,a,’r’);

Axis([-2 2 -2 2]);

-2 -1.5 -1 -0.5 0 0.5 1 1.5 2-2

-1.5

-1

-0.5

0

0.5

1

1.5

2

Error Bars• In addition to markers, matlab can generate error bars for each

datapoint using the errorbar command

– errorbar(x,y,e) or errorbar(x,y,ll,lu);

– Will generate line plus error bars at y+/-e or (y-ll,y+lu)

t2 = 0:1:10;

f = t2+(rand(1,length(t2))-0.5);

err1 = 0.1*f;

err2_l = 0.1*f;

err2_u = 0.25*f;

errorbar(t2,f,err1);

figure;

errorbar(t2,f,err2_l, err2_u);

-2 0 2 4 6 8 10 120

2

4

6

8

10

12

-2 0 2 4 6 8 10 120

2

4

6

8

10

12

14

Page 33: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

33

Subplots• So far we have only been generating individual plots

• Matlab can also generate a matrix of plots using the subplot command

figure;

subplot(2,2,1)

plot(t,a);

subplot(2,2,2)

plot(t,b);

subplot(2,2,3)

plot(t,c);

subplot(2,2,4)

plot(t,d);

0 0.5 1 1.5 20

0.5

1

1.5

2

2.5

3

3.5

4

0 0.5 1 1.5 2-1

-0.5

0

0.5

1

0 0.5 1 1.5 20

0.2

0.4

0.6

0.8

1

0 0.5 1 1.5 2-1

-0.5

0

0.5

1

Quick Assignment 2

• Generate a 3x1 array

of figures, each with a

title

• Axis range of plots 1

and 2 should be 0 to 1

on x and y

• Plot 1 should include

function a and b (color

code)

• Plot 2 should include

c and d (color code)

• Plot 3 should include f

with error bars of your

liking

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

0.5

1Functions a and b

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

0.5

1Functions c and d

-2 0 2 4 6 8 10 120

10

20function f with errorbars

Quick Assignment 2

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

0.5

1Functions a and b

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

0.5

1Functions c and d

-2 0 2 4 6 8 10 120

10

20function f with errorbars

figure

subplot(3,1,1)

plot(t,a,t,b,'r');

axis([0 1 0 1]);

title('Functions a and b')

subplot(3,1,2)

plot(t,c,t,d,'m');

axis([0 1 0 1]);

title('Functions c and d')

subplot(3,1,3)

errorbar(t2,f,err1);

title('function f with errorbars')

Bar Graphs• So far we have focused on line/scatter plots, the other most common

plot type is a bar graph

• Matlab bar(x,y,width) command will generate a bar graph that is

related to the underlying functions where the width of each bar is

specified by width (default = 1);

• Can be used with subplot and all the other features we have

discussed so far

t3 = 0:1:25;

f = sqrt(t3);

bar(t3,f);

-5 0 5 10 15 20 25 300

0.5

1

1.5

2

2.5

3

3.5

4

4.5

5

Histograms• Matlab hist(y,m) command will generate a frequency histogram of

vector y distributed among m bins

• Also can use hist(y,x) where x is a vector defining the bin centers

– Note you can use histc function if you want to define bin edges instead

• Can be used with subplot and all the other features we have

discussed so far

hist(b,10);

Figure;

Hist(b,[-1 -0.75 0 0.25 0.5 0.75 1]);

-1.5 -1 -0.5 0 0.5 1 1.50

5

10

15

20

25

30

35

40

-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 10

5

10

15

20

25

30

35

40

45

Quick Assignment 3

• Generate the following data set

– It results in multiple noisy repeats of some trial

• Create mean_x to be the mean of all the trials at each

point of x

• Create std_x to be the standard deviation of all trials at

each point of x

• Add labels and titles

t = 0:0.1:1

for(i=1:25)

x(i,:) = exp(-10.*t) + 0.5*(rand(1,length(t))-0.5);

end

Page 34: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

34

Quick Assignment 3

• Make a plot that is to include 2 subplots

• Plot #1:– Plot each individual trial (25 lines) in thin dotted black lines,

• tip: remember about how matlab interprets matricies for the plot command.

– Plot the mean of the trials with a thick, red, dashed line and error lines surrounding each datapoint that correspond to the standard deviation of each of the points

• Plot #2:– A histogram that expresses the distribution of the signal at the

end of each trial (last sample)

Quick Assignment 3

-0.2 0 0.2 0.4 0.6 0.8 1 1.2-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

1.2

1.4Repeats of a Given Task

Repeat

Err

or

Rate

-0.25 -0.2 -0.15 -0.1 -0.05 0 0.05 0.1 0.15 0.2 0.250

1

2

3

4

5Distribut ion of Endpoint Position

Deviation (mm)

Occ

ura

nces

t = 0:0.1:1

for(i=1:25)

x(i,:) = exp(-10.*t) + 0.5*(rand(1,length(t))-0.5);

end

mean_x = mean(x);

std_x = std(x);

figure

subplot(2,1,1)

plot(t,x,'k'); hold on;

errorbar(t,mean_x,std_x,'--r','LineWidth', 3);

title('Repeats of a Given Task')

xlabel('Repeat');

ylabel('Error Rate');

subplot(2,1,2)

hist(x(:,11),10)

title('Distribution of Endpoint Position');

xlabel('Deviation (mm)')

ylabel('Occurances')

Quick Assignment 3

-0.2 0 0.2 0.4 0.6 0.8 1 1.2-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

1.2

1.4Repeats of a Given Task

Repeat

Err

or

Rate

-0.25 -0.2 -0.15 -0.1 -0.05 0 0.05 0.1 0.15 0.2 0.250

1

2

3

4

5Distribution of Endpoint Position

Deviation (mm)

Occura

nces

Recap

• Learned about basic 2D plot functions

– plot,bar,hist

• Dealing with multiple plots and graphs

– Hold, figure, subplot

• Discussed adding features to graphs

– Xlabel,title,legend,C

3D Plots

• Matlab provides a wide range of 3D plot

options, we will talk about 3 different plot

types.– Mesh, Surf, Contour

Dataset

• Try [x,y,z] = peaks(25)– Does this work?

• If not, lets create an arbitrary dataset

– x=-10:10; y = -10:10; z=x.^2’*y.^2;

Page 35: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

35

Mesh

• Connects a series of discrete data points

with a mesh– mesh(x,y,z) where X(i) and Y(j) are the intersections of

the mesh and Z(i,j) is the height at that intersection

– mesh(Z) assumes X and Y are simple 1..N and 1..M

Surf

• Very similar to mesh, with filled grid

Contour

• Projection of equal heights of 3D plot onto a

2D plane

• Use like surf or mesh – contour(x,y,z)

Meshc,surfc

• Combination surface/mesh and contour plot

• Use like surf or mesh – meshc(x,y,z)

Plot3• Plots lines and points in space, just like plot but now for an

(x,y,z) pair

• Plot3(x,y,z), each a vector of equal length

• Use all the same specfiers to generate colors, line-types, etc.

Plot commands

• Note that almost all 2D plotting commands

such as xlabel, ylabel, title will still work in

3D plots

• 3D plots can be added as subplots just like

any other plot type

• Some other special features and functions

existC

Page 36: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

36

View

• Changes the view of the current 3D plot– view(az,el)

– Az = azimuth (rotation around z-axis)

– El = Elevation (rotation around xy-plane)

• Useful rotations (0,0),(90,0)

Colorbar

• For the 3D plots, it is useful to add a

colorbar to the figure to indicate height.

• Colorbar(‘vert’) adds a vertical colorbar

• Colorbar(‘horiz) adds a horizontal colorbar

caxis

• Allows you to set the range of colors in the plot.

• Caxis([min max]) will choose the range of colors

from the current color map to assign to the plot.

Values outside this range will use the min/max

available

Colormap

• Plenty of other controls to personalize the

plot– colormap colormap_name sets to new map

– Colormap (sets the types of colors that appear in 3D

plot). These can be custom of one of several premade

– Hsv, jet, autumn, vga, summer, C

– See help graph3D for more

– Use colormapeditor function for graphical selection of

color map

ColormapLoading Binary Data

Page 37: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

37

loading Binary Data

A. Importing Text Data

B. Binary Encoding

C. Binary Data Formats

D. Exercise

A. Review:

Importing Text Data• Basic issue:

– How do we get data from other sources into

Matlab so that we can play with it?

• Other Issues:

– Where do we get the data?

– What types of data can we import?

• Lots of options to load files

– load for basics

– fscanf for complex

– textread for any text

– xlsread for Excel worksheets

load

• Command opens and imports data from a standard ASCII file into a matlab variable

• Usage: var_name = load(‘filename’)

• Restrictions

– Data must be constantly sized

– Data must be ASCII

– No other characters

load

• Works for simple and unstructured code

• Powerful and easy to use but limited

• Will likely force you to manually handle

simplifying data which is prone to error

• More complex functions are more flexible

File Handling

• f* functions are associated with file opening,

reading, manipulating, writing, C

• Basic Functions of Interest for opening and

reading generic files in matlab

– fopen

– fclose

– fseek/ftell/frewind

– fscanf

– fgetl

Page 38: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

38

fopen

• Opens a file object in matlab that points to

the file of interest

• fid = fopen(‘filepath’)

• fid is an integer that represents the file

– Can open multiple files and matlab will assign

unique fids

fclose

• When you are done with a file, it is a good idea

to close it especially if you are opening many

files

• fclose(fid)

What is a File?

• A specific organization of data

• In matlab it is identified with a fid

• Location is specified with a pointer that can be

moved around

file_name

fid

Pointer

Moving the Pointer

• We already know how to assign a fid (fopen)

• To find where the file is pointing:

– x = ftell(fid)

• To point somewhere else

– fseek(fid,offset,origin)

• Move pointer in file fid by offset relative to origin

– Origin can be beginning, current, end of file

• To point to the beginning

– frewind(fid)

Getting Data

• Why move the pointer around?

– Get somewhere in the file from where you want data

• fscanf(fid,format,size)

• Format

– You have to tell matlab the type of data it should be expecting in the text file so that it can convert it

• ‘%d’, ‘%f’, ‘%c’

• Size

– You can specify how to organize the imported data• [m,n] – import the data as m by n, n can be infinite

• Be careful because matlab will mangle your data and not tell you

Getting Data

• fgetl returns the next line of the file as a

character array

• You may need to convert these to numbers

>> fid1 = fopen(‘test1.txt’);

>> a_str = fgetl(fid1)

a_str = 1 2

>> a_num = str2num(a_str)

a_num = [1 2]

Page 39: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

39

B. Binary Encoding

• All data files are binary encoded

• ASCII text format is generally the easiest

because it is relatively simple, easy to visualize

in a text editor, and is a common output format

BUT

• ASCII text is not the fastest or the most efficient

way of encoding data

• Not all data files are ASCII!

B. Binary Encoding

• Binary data consists of sequences of 0’s and 1’s

• 10101010101010101000010111110111101011

• Depending on the encoding used, individual meaningful values will occur every 4, 8, 16, 32 or 64 bits

• For a tutorial on converting between binary and decimal numbers see: http://www.rwc.uc.edu/koehler/comath/11.html

B. Binary Encoding

• Binary data consists of sequences of 0’s and 1’s

• 1010 1010 1010 1010 1000 0101 1111

• Depending on the encoding used, individual meaningful values will occur every 4, 8, 16 or 32 bits

B. Binary Encoding

• Binary data consists of sequences of 0’s and 1’s

• 10101010 10101010 10000101 11110111

• Depending on the encoding used, individual meaningful values will occur every 4, 8, 16 or 32 bits

B. Binary Encoding

• Binary data consists of sequences of 0’s and 1’s

• 1010101010101010 1000010111110111

• Depending on the encoding used, individual meaningful values will occur every 4, 8, 16 or 32 bits

B. Binary Encoding

• Each group of bits can represent a value, character, delimiter, command, instruction ect.

• Generally binary data is divided into 8 bit (1 byte) segments

• 00000000 = zero

• 11111111 = 255

• IT IS VERY IMPORTANT TO KNOW WHAT FORMAT THE DATA IS IN BEFORE YOU CAN READ IT!

Page 40: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

40

ASCII ENCODING

• ASCII: American Standard Code for Information Interchange (1968).

• ASCII every character is coded by only seven bits of information. The eighth bit is ignored (it can be a zero or one).

• ASCII consists of 127 characters which include uppercase, lowercase, spaces and formatting characters

•See www.asciitable.com for the full ascii table

ASCII vs Simple Binary

Encoding• ASCII requires 1 byte to be used for every character

Data Table:

105 124 27

101 102 111

• In ascii 1 byte is used for every character, space and carriage return = 23 bytes

• If this was encoded in a simple 8 bit binary representation this would only use 11 bytes (1 byte for every number and space)

Binary Precision

• The number of bits used to represent a value determines how large or small that value can be

•8 bits 0 to 256

•16 bits 0 to 65536

•32 bits 0 to 4.2950e+009

•Precision also determines how many decimal places can be represented

'schar' Signed character; 8 bits

'uchar' Unsigned character; 8 bits

'int8' Integer; 8 bits

'int16' Integer; 16 bits

'int32' Integer; 32 bits

'int64' Integer; 64 bits

'uint8' Unsigned integer; 8 bits

'uint16' Unsigned integer; 16 bits

'uint32' Unsigned integer; 32 bits

'uint64' Unsigned integer; 64 bits

* The first bit denotes

the sign if the integer

or character is signed.

C. Binary Formats:

Integers and Characters

Readable Binary Data Formats

Floating Point RepresentationUsed for numbers that require decimal representation (real numbers)

•Established by IEEE (Institute of Electrical and Electronics Engineers )

• Encoded in 32 (single precision) or 64 bits (double precision)

• Single precision(short): 32 bits 1 bit for the sign, 8 bits for the exponent, and 23 bits for the mantissa.

• Double precision(Long) Real: 64 bits 1 bit for the sign, 11 bits for the exponent, and 52 bits for the mantissa.

Readable Binary Data Formats

Floating Point Representation

• By default matlab stores all values with double precision

• The functions realmax and realmin return max and min value representations

'float32‘, ‘single’ Floating-point; 32 bits

'float64', 'double' Floating-point; 64 bits

Page 41: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

41

Specifying Machine Formats

• The computer system used to record or save the binary data in unique addressing orders

• In order to load binary data from a particular system, Matlab needs to know the machine format

•You can use the fopen function to determine the machine format

[filename, mode, machineformat] = fopen(fid)

Binary File Machine Formats

'ieee-be' or 'b‘: IEEE floating point with big-endian byte ordering

'ieee-le' or 'l' : IEEE floating point with little-endian byte ordering

'ieee-be.l64' or 's‘: IEEE floating point with big-endian byte ordering

and 64-bit long data type

'ieee-le.l64' or 'a‘: IEEE floating point with little-endian byte ordering

and 64-bit long data type

'native' or 'n' : Numeric format of the machine on which MATLAB

is running (the default)

'vaxd' or 'd' : VAX D floating point and VAX ordering

'vaxg' or 'g' : VAX G floating point and VAX ordering

Reading Binary Data

• The function fread() performs all binary data reading in matlab

Syntax

A = fread(fid)

A = fread(fid, count)

A = fread(fid, count, precision)

A = fread(fid, count, precision, skip)

A = fread(fid, count, precision, skip, machineformat)

[A, count] = fread(...)

Reading Binary DataInput Arguments:

Count: x: read x elements

Inf: read to end of file

[m,n]: read enough to fill a m by n matrix

Precision: Specify input data format eg. Int8, int16, short,

longC see previous slides

Skip: Skip specified number of bits between

segments specified by the Precision argument

MachineFormat: Specify machine format 'ieee-be‘, 'ieee-le‘C..

See previous slides

Implementation of Neural Network

using NN Toolbox Version

3.0.1

• 1. Loading data source.

• 2. Selecting attributes required.

• 3. Decide training, validation, and testing data.

• 4. Data manipulations and Target generation.

– (for supervised learning)

• 5. Neural Network creation (selection of

network architecture) and initialisation.

• 6. Network Training and Testing.

• 7. Performance evaluation.

Loading data

• load: retrieve data from disk.

– In ascii or .mat format. Save variables in matlab

environment and load back

>> data = load(‘wtest.txt’);

>> whos data;

Name Size Bytes Class

data 826x7 46256 double array

Page 42: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

42

Matrix manipulation

• stockname = data(:,1);

• training = data([1:100],:)

• a=[1;2]; a*a’ => [1,2;2,4];

• a=[1,2;2,4]; a.*a => [1,4;4,16];

for all

Start for 1

1 2

2 4

1 4

4 16

Neural Network Creation and

Initialisation• net = newff(PR,[S1 S2...SNl],{TF1 TF2...TFNl},BTF,BLF,PF)

• Description

• NEWFF(PR,[S1 S2...SNl],{TF1 TF2...TFNl},BTF,BLF,PF) takes,

• PR - Rx2 matrix of min and max values for R input elements.

• Si - Size of ith layer, for Nl layers.

• TFi - Transfer function of ith layer, default = 'tansig'.

• BTF - Backprop network training function, default = 'trainlm'.

• BLF - Backprop weight/bias learning function, default = 'learngdm'.

• PF - Performance function, default = 'mse’ and returns an

• N layer feed-forward backprop network.

Number of inputs

decided by PR

S1: number

hidden neurons

S2: number of

ouput neuron

>> PR = [-1 1; -1 1; -1 1; -1 1];

-1 1

-1 1

-1 1

-1 1Min Max

neuron 1

Neural Network Creation• newff : create a feed-forward network.

• Description

• NEWFF(PR,[S1 S2...SNl],{TF1 TF2...TFNl},BTF,BLF,PF) takes,

• PR - Rx2 matrix of min and max values for R input elements.

• Si - Size of ith layer, for Nl layers.

• TFi - Transfer function of ith layer, default = 'tansig'.

• BTF - Backprop network training function, default = 'trainlm'.

• BLF - Backprop weight/bias learning function, default = 'learngdm'.

• PF - Performance function, default = 'mse’ and returns an

• N layer feed-forward backprop network.

TF1: logsig

TF2: logsig

>> net = newff([-1 1; -1 1; -1 1; -1 1], [4,1], {‘logsig’ ‘logsig’}); Number of inputs

decided by PR

Network Initialisation

• Initialise the net’s weighting and biases

• >> net = init(net); % init is called after

newff

• re-initialise with other function:– net.layers{1}.initFcn = 'initwb';

– net.inputWeights{1,1}.initFcn = 'rands';

– net.biases{1,1}.initFcn = 'rands';

– net.biases{2,1}.initFcn = 'rands';

Network Training

• The overall architecture of your neural network is store

in the variable net;

• We can reset the variable inside.

net.trainParam.epochs =1000; (Max no. of epochs to train) [100]

net.trainParam.goal =0.01; (stop training if the error goal hit) [0]

net.trainParam.lr =0.001; (learning rate, not default trainlm) [0.01]

net.trainParam.show =1; (no. epochs between showing error) [25]

net.trainParam.time =1000; (Max time to train in sec) [inf]

Network Training(cont’d)

train : train the network with its architecture.

Description

TRAIN(NET,P,T,Pi,Ai) takes,

NET - Network.

P - Network inputs.

T - Network targets, default = zeros.

Pi - Initial input delay conditions, default = zeros.

Ai - Initial layer delay conditions, default = zeros.>> p = [-0.5 1 -0.5 1; -1 0.5 -1 0.5; 0.5 1 0.5 1; -0.5 -1 -0.5 -1];

-0.5 1 -0.5 1

-1 0.5 -1 0.5

0.5 1 0.5 1

-0.5 -1 -0.5 -1Training

pattern 1

For

neuron 1

Page 43: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

43

Network Training(cont’d)

• train : train the network with its architecture.

• Description

• TRAIN(NET,P,T,Pi,Ai) takes,

• NET - Network.

• P - Network inputs.

• T - Network targets, default = zeros.

• Pi - Initial input delay conditions, default = zeros.

• Ai - Initial layer delay conditions, default = zeros.

>> p = [-0.5 1 -0.5 1; -1 0.5 -1 0.5; 0.5 1 0.5 1; -0.5 -1 -0.5 -1];

>> net = train(net, p, t);

>> t = [-1 1 -1 1];

-1 1 -1 1

Training

pattern 1

Simulation of the network

• [Y] = SIM(model, UT)

• Y : Returned output in matrix or structure format.

• model : Name of a block diagram model.

• UT : For table inputs, the input to the model is interpolated.

>> UT = [-0.5 1 ; -0.25 1; -1 0.25 ; -1 0.5];

-0.5 1.00

-0.25 1.00

-1.00 0.25

-1.00 0.50Training

pattern 1

For

neuron 1

>> Y = sim(net,UT);

Performance Evaluation

• Comparison between target and network’s

output in testing set.(generalisation ability)

• Comparison between target and network’s

output in training set. (memorisation ability)

• Design a function to measure the

distance/similarity of the target and output, or

simply use mse for example.

Nonlinear Curve Fitting

Nonlinear Curve Fitting

A. Linear Curve Fitting ReviewA. Calculating Linear Regressions

B. Least Squares vs Robust Fit

B. Figure Window Curve Fitting Interface

C. Curve Fitting ToolboxA. Curve Fitting Strategies

B. Calculating Goodness of Fit

Required Toolboxes:

A. Statistics Toolbox

B. Curve Fitting Toolbox

C. Spline Toolbox

Page 44: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

44

Purpose of Curve Fitting:

• Curve fitting matches mathematical

models to data

• Is a powerful tool if it can be used to

make accurate predictions

Nonlinear Curve Fitting

Part A: Linear Curve Fitting Review

Curve Fitting

• Plotting a line of best fit in Matlab can be

performed using either a traditional least

squares fit or a robust fitting method.

• Robust Vs Least Squares Demo (robustdemo)

1 2 3 4 5 6 7 8 9 10

-2

0

2

4

6

8

10

12

Least squares

Robust

Curve Fitting• A least squares linear fit minimizes the square of the

distance between every data point and the line of best fit

polyfit(X,Y,N) finds the coefficients of a polynomial P(X) of degree N that fits the data

Uses least-square minimization

N = 1 (linear fit)

[P] = polyfit(X,Y,N) returns P, a matrix containing the slope and the x intercept for a linear fit

[Y] = polyval(P,X) calculates the Y values for every X point on the line of best fit

Curve Fitting• Example:

• Draw a line of best fit using least squares approximation for the data in exercise 2

[var1, var2] = textread('testdata2.txt','%f%f','headerlines',1)

P = polyfit(var1,var2,1);

Y = polyval(P,var1);

close all

figure(1)

hold on

plot(var1,var2,'ro')

plot(var1,Y)

-2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5-3

-2

-1

0

1

2

3

Curve Fitting• A least squares linear fit minimizes the square

of the distance between every data point and the line of best fit

• A robust fit is less effected by small numbers of outliers

• P = robustfit(X,Y) returns the vector B of the y intercept and slope, obtained by performing robust linear fit

• ‘robustdemo’ gives a good graphical example comparing robust and least squares line fitting

Page 45: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

45

Curve FittingExample:

• Draw a line of best fit using robust fit approximation for the data in exercise 2

[var1, var2] = textread('testdata2.txt','%f%f','headerlines',1)

P = robustfit(var1,var2,1);

Y = polyval([P(2),P(1)],var1);

close all

figure(1)

hold on

plot(var1,var2,'ro')

plot(var1,Y)

-2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5-3

-2

-1

0

1

2

3

Higher Order Curve Fitting

Method 1• Polyfit can be used to calculate any polynomial fitting

function of the form:

• y = polyval(p,x) returns the value of a polynomial of degree n evaluated at x. The input argument p is a vector of length n+1 whose elements are the coefficients in descending powers of the polynomial to be evaluated.

• x can be a matrix or a vector. In either case, polyval evaluates p at each element of x.

Curve Fitting

Example:

• Calculate a polynomial fit of

order 2, 3, and 4 for the data in

the previous example

Curve Fitting Example• 2nd Order Polynomial Fit:

%read data[var1, var2] =

textread(‘week8_testdata2.txt','%f%f','headerlines',1)

% Calculate 2nd order polynomial fit

P2 = polyfit(var1,var2,2);

Y2 = polyval(P2,var1);

%Plot fit

close all

figure(1)

hold on

plot(var1,var2,'ro')

[sortedvar1, sortind] = sort(var1)

plot(sortedvar1,Y2(sortind),'b*-')

2nd Order Polynomial Fit:

-2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5-3

-2

-1

0

1

2

3

Curve Fitting Example• Add 3rd Order Polynomial Fit:

% Calculate 3rd order polynomial fit

P3 = polyfit(var1,var2,3);

Y3 = polyval(P3,var1);

%Add fit to figure

figure(1)

plot(sortedvar1,Y3(sortind),’g*-')

Page 46: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

46

-2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5-3

-2

-1

0

1

2

3

2nd Order Polynomial Fit:

3rd Order Polynomial Fit: Curve Fitting Example• Add 4th Order Polynomial Fit:

% Calculate 4th order polynomial fit

P4 = polyfit(var1,var2,4);

Y4 = polyval(P4,var1);

%Add fit to figure

figure(1)

plot(sortedvar1,Y4(sortind),’k*-')

-2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5-3

-2

-1

0

1

2

3

2nd Order Polynomial Fit:

3rd Order Polynomial Fit:4th Order Polynomial Fit:

Assessing Goodness of Fit

• The tough part of polynomial regression is

knowing that the "fit" is a good one.

• Determining the quality of the fit requires

experience, a sense of balance and some

statistical summaries.

Assessing Goodness of Fit

• One common goodness of fit involves a least-

squares approximation. This describes the distance

of the entire set of data points from the fitted curve.

The normalization of the residual error

minimizing the square of the sum of squares of all

residual errors.

• The coefficient of determination (also referred to

as the R2 value) for the fit indicates the percent of

the variation in the data that is explained by the

model.

Assessing Goodness of Fit

• This coefficient can be computed via the commands:

ypred = polyval(coeff,x); % predictions

dev = y - mean(y); % deviations - measure of spread

SST = sum(dev.^2); % total variation to be accounted for

resid = y - ypred; % residuals - measure of mismatch

SSE = sum(resid.^2); % variation NOT accounted for

normr = sqrt(SSE) % the 2-norm of the vector of the residuals for the fit

Rsq = 1 - SSE/SST; % R2 Error (percent of error explained)

• The closer that Rsq is to 1, the more completely the fitted model "explains" the data.

Page 47: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

47

Example:

• Calculate the R2 error and Norm

of the residual error for a 2nd

order polynomial fit for the data

in the previous example

Assessing Goodness of Fit

-2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5-3

-2

-1

0

1

2

3

Assessing Goodness of Fit

Example Solution

% recall var1 contains x values and var2 contains y values of data points

ypred = polyval(P2,var1);

dev = var2 - mean(2); SST = sum(dev.^2); resid = var2 - ypred; SSE = sum(resid.^2);normr = sqrt(SSE); % residual normRsq = 1 - SSE/SST; % R2 Error

Normr = 5.7436

Rsq = 0.8533

• The residual norm and R2 error indicate goodness of fit

2nd Order Polynomial Fit:

Limitations of Polyfit

• Only finds a least squares best polynomial

function fit

• Cannot be used to interpolate curves or fit other

standard functions

• Requires several lines of code and the polyval()

function

Higher Order Curve Fitting

Method 2• Curve Fitting Tools can be accessed directly

from the figure window:

• To access curve fitting directly from the figure window, select ‘basic fitting’ from the ‘tools’ pulldown menu in the figure window.

• This is a quick and easy method to calculate and visualize a variety of higher order functions including interpolation

Higher Order Curve Fitting

Method 2

• Plot data from previous exercise

• Try a variety of curve fittings

Higher Order Curve Fitting

Caution:• Higher order polynomial fits should

only be used when a large number of data points are available

• Higher order polynomial fitting functions may fit more the data more accurately but may not yield an interpretable model

Page 48: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

48

Higher Order Curve Fitting

Method 2

Curve Fitting from Figure Window Advantages:

• Quick and easy to plot fits from existing data

Easy accessibility of:

• Function Coefficients• Fitting Equations • Residual errors • The value of fitting function at any value of x

Higher Order Curve Fitting

Method 3

• Curve Fitting Toolbox

• The curve fitting toolbox is accessible by

the ‘cftool’ command

• Very powerful tool for data smoothing,

curve fitting, and applying and evaluating

mathematical models to data points

Curve Fitting Toolbox

1. Loading Data Sets

• Before you can import data into the Curve Fitting Tool, the data variables must exist in the MATLAB workspace.

• You can import data into the Curve Fitting Tool with the Data GUI. You open this GUI by clicking the Data button on the Curve Fitting Tool.

• The Data Sets pane allows you to:

Import predictor (X) data, response (Y) data, and weights. – If you do not import weights, then they are assumed to be 1 for all data

points.

• Specify the name of the data set.

• Preview the data.

• Click the Create data set button to complete the data import process.

Curve Fitting Toolbox

2. Smoothing Data Points

• If your data is noisy, you might need to apply a smoothing algorithm to expose its features, and to provide a reasonable starting approach for parametric fitting.

Curve Fitting Toolbox

2. Smoothing Data Points

• If your data is noisy, you might need to apply a smoothing algorithm to expose its features, and to provide a reasonable starting approach for parametric fitting.

The two basic assumptions that underlie smoothing are:

1. The relationship between the response data and the predictor data is smooth.

2. The smoothing process results in a smoothed value that is a better estimate of the original value because the noise has been reduced.

Curve Fitting Toolbox2. Smoothing Data Points

• The Curve Fitting Toolbox supports these smoothing methods:

Moving Average Filtering: Lowpass filter that takes the average of neighboring data points.

Lowess and Loess: Locally weighted scatter plot smooth. These methods use linear least squares fitting, and a first-degree polynomial (lowess) or a second-degree polynomial (loess). Robust lowess and loess methods that are resistant to outliers are also available.

Savitzky-Golay Filtering: A generalized moving average where you derive the filter coefficients by performing an unweighted linear least squares fit using a polynomial of the specified degree.

Page 49: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

49

Curve Fitting Toolbox

Smoothing Method and Parameters

Span: The number of data points used to compute each

smoothed value.

• For the moving average and Savitzky-Golay methods, the

span must be odd. For all locally weighted smoothing

methods, if the span is less than 1, it is interpreted as the

percentage of the total number of data points.

Degree: The degree of the polynomial used in the Savitzky-

Golay method. The degree must be smaller than the span.

Curve Fitting Toolbox

Excluding Data Points

• It may be necessary to remove outlier points

from a data set before attempting a curve fit

• Typically, data points are excluded so that

subsequent fits are not adversely affected.

• Can help improve a mathematical model’s

predictability

Curve Fitting ToolboxExcluding Data Points

The Curve Fitting Toolbox provides two methods to exclude data:

• Marking Outliers: Outliers are defined as individual data points that you exclude because they are inconsistent with the statistical nature of the bulk of the data.

• Sectioning: Sectioning excludes a window of response or predictor data. For example, if many data points in a data set are corrupted by large systematic errors, you might want to section them out of the fit.

• For each of these methods, you must create an exclusion rule, which captures the range, domain, or index of the data points to be excluded.

Curve Fitting Toolbox

Plotting Fitting Curves

• You fit data with the Fitting GUI. You open this GUI by clicking the Fitting button on the Curve Fitting Tool.

Curve Fitting ToolboxPlotting Fitting Curves

The Fit Editor allows you to:

• Specify the fit name, the current data set, and the exclusion rule.

• Explore various fits to the current data set using a library or custom equation, a smoothing spline, or an interpolant.

• Override the default fit options such as the coefficient starting values.

• Compare fit results including the fitted coefficients and goodness of fit statistics.

Curve Fitting ToolboxPlotting Fitting Curves

The Table of Fits allows you to:

• Keep track of all the fits and their data sets for

the current session.

• Display a summary of the fit results.

• Save or delete the fit results.

Page 50: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

50

Curve Fitting ToolboxAnalyzing Fits

• You can evaluate (interpolate or extrapolate),

differentiate, or integrate a fit over a specified

data range with the Analysis GUI. You open this

GUI by clicking the Analysis button on the

Curve Fitting Tool.

Curve Fitting ToolboxAnalyzing Fits

To Test your Model’s Predictions:

• Enter the appropriate MATLAB vector in the Analyze at Xi field.

• Select the Evaluate fit at Xi check box.

• Select the Plot results and Plot data set check boxes.

• Click the Apply button.

• The numerical extrapolation results are displayed

Curve Fitting Toolbox

Saving Your Work

• You can save one or more fits and the associated fit results as variables to the MATLAB workspace.

• You can then use this saved information for documentation purposes, or to extend your data exploration and analysis.

• In addition to saving your work to MATLAB workspace variables, you can:

1. Save the session

2. Generate an M-file

Curve Fitting ToolboxSaving Your Work

Generating an M-file:

• You may want to generate an M-file so that you can

continue data exploration and analysis from the

MATLAB command line.

• You can run the M-file without modification to recreate

the fits and results that you created with the Curve

Fitting Tool, or you can edit and modify the file as

needed

Curve Fitting Toolbox

Saving Your Work

Generating an M-file:

The M-file captures:

• All data set variable names, associated fits, and residuals

• Fit options such as whether the data should be normalized, the fit starting points, and the fitting method

• You can recreate the saved fits in a new figure window by typing the name of the M-file at the MATLAB command line.

• Note that you must provide the appropriate data variables as inputs to the M-file. These variables are given in the M-file help.

Curve Fitting Toolbox

Exercise

1. Load the data file ‘week8_testdata2.txt’ from week 8

2. Use the curve fitting toolbox smooth the data using a 5 point moving average

3. Exclude all points with y values less then -1

4. Fit a 4th order polynomial through the smoothed data points

5. Generate an m-file that can be used to re-calculate the fitted curve

Page 51: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

51

Statistics II

Statistics II

A. Basic Matlab Statistics ReviewA. Mean, Median, Variance

B. Statistics ToolboxA. Simple Parametric and Non-parametric statistical tests

C. Simple Statistical PlottingA. Histograms

B. Box Plots

D. AnovasA. 1 Way Unrelated Design

B. Post Hoc vs A Priori Comparisons

C. N-Way Anovas

D. Related (Repeated Measures) Design

E. Unrelated (Between Groups) Design

Required Toolboxes:

Statistics Toolbox

Statistics II

Part A: Basic Matlab Statistics Review

Part A: Basics

• The Matlab installation contains basic statistical

tools.

• Including, mean, median, standard deviation,

error variance, and correlations

• More advanced statistics are available from the

statistics toolbox and include parametric and

non-parametric comparisons, analysis of

variance and curve fitting tools

Mean and MedianMean: Average or mean value of a distribution

Median: Middle value of a sorted distribution

M = mean(A), M = median(A)

M = mean(A,dim), M = median(A,dim)

M = mean(A), M = median(A): Returns the mean or median value of vector A.

If A is a multidimensional mean/median returns an array of mean values.

Example:

A = [ 0 2 5 7 20] B = [1 2 3

3 3 6

4 6 8

4 7 7];

mean(A) = 6.8

mean(B) = 3.0000 4.5000 6.0000 (column-wise mean)

mean(B,2) = 2.0000 4.0000 6.0000 6.0000 (row-wise mean)

Page 52: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

52

Mean and MedianExamples:

A = [ 0 2 5 7 20] B = [1 2 3

3 3 6

4 6 8

4 7 7];

Mean:mean(A) = 6.8

mean(B) = 3.0 4.5 6.0 (column-wise mean)

mean(B,2) = 2.0 4.0 6.0 6.0 (row-wise mean)

Median:median(A) = 5

median(B) = 3.5 4.5 6.5 (column-wise median)

median(B,2) = 2.0

3.0

6.0

7.0 (row-wise median)

Standard Deviation and Variance

• Standard deviation is calculated using the std() function

• std(X) : Calcuate the standard deviation of vector x

• If x is a matrix, std() will return the standard deviation of each column

• Variance (defined as the square of the standard deviation) is calculated

using the var() function

• var(X) : Calcuate the variance of vector x

• If x is a matrix, var() will return the standard deviation of each column

Standard Error of the Mean

• Often the most appropriate measure of

error/variance is the standard error of the mean

• Matlab does not contain a standard error function

so it is useful to create your own.

• The standard error of the mean is defined as the

standard deviation divided by the square root of

the number of samples

Statistics II

Part B: Parametric and Non-parametric

statistical tests

Comparison of Means

• A wide variety of mathametical methods exist

for determining whether the means of different

groups are statistically different

• Methods for comparing means can be either

parametric (assumes data is normally

distributed) or non-parametric (does not assume

normal distribution)

Parametric Tests - TTEST

[H,P] = ttest2(X,Y)

Determines whether the means from matrices X

and Y are statistically different.

H return a 0 or 1 indicating accept or reject nul

hypothesis (that the means are the same)

P will return the significance level

Page 53: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

53

Parametric Tests - TTEST

[H,P] = ttest2(X,Y)

Determines whether the means from matrices X

and Y are statistically different.

H return a 0 or 1 indicating accept or reject nul

hypothesis (that the means are the same)

P will return the significance level

Parametric Tests - TTEST

Example:

For the data from Week 8

exercise 3

[H,P] = ttest2(var1,var2)

>> [H,P] = ttest2(var1,var2)

H =1

P = 0.00000000000014877

-3 -2 -1 0 1 2 3-4

-3

-2

-1

0

1

2

3

4

5

Va

ria

ble

1

Variable 2

Non-Parametric Tests Ranksum

• The wilcoxin ranksum test assesses whether

the means of two groups are statistically

different from each other.

• This test is non-parametric and should be used

when data is not normally distributed

• Matlab implements the wilcoxin ranksum test

using the ranksum() function

ranksum(X,Y) statistically compares the means of

two data distributions X and Y

Non-Parametric Tests -

RankSumExample:

For the data from week 8

exercise 3

[P,H] = ranksum(var1,var2)

P = 1.1431e-014

H = 1

-3 -2 -1 0 1 2 3-4

-3

-2

-1

0

1

2

3

4

5

Va

ria

ble

1

Variable 2

Statistics II

Part C: Simple Statistical PlottingA. Histograms

B. Box Plots

Histograms

• Histograms are useful for showing the pattern

of the whole data set

• Allows the shape of the distribution to be easily

visualized

Page 54: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

54

Histograms• Matlab hist(y,m) command will generate a frequency

histogram of vector y distributed among m bins

• Also can use hist(y,x) where x is a vector defining the bin

centers

Example:>>b=sin(2*pi*t)

>>hist(b,10); >>hist(b,[-1 -0.75 0 0.25 0.5 0.75 1]);

-1.5 -1 -0.5 0 0.5 1 1.50

5

10

15

20

25

30

35

40

-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 10

5

10

15

20

25

30

35

40

45

Histograms• The histc function is a bit more powerful and allows bin

edges to be defined

[n, bin] = histc(x, binrange)

x = statistical distribution

binrange = the range of bins to plot eg: [1:1:10]

n = the number of elements in each bin from vector x

bin = the bin number each element of x belongs

• Use the bar function to plot the histogram

Histograms• The histc function is a bit more powerful and allows bin

edges to be defined

Example:>> test = round(rand(100,1)*10)

>> histc(test,[1:1:10])

>> Bar(test)

1 2 3 4 5 6 7 8 9 100

2

4

6

8

10

12

14

Box Plots

• Box plots are useful to graphically display the

mean and variance of distributions, as well as

the interquartile range and outliers

1

0

2

4

6

8

10

12

14

16

Va

lue

s

Column Number

Box Plots• Matlab function boxplot(x) will generate a boxplot

of the distribution defined by x

Example:% add outlier to test distribution

>>test(101) = 16

>>boxplot(test)

1

0

2

4

6

8

10

12

14

16

Valu

es

Column Number

Box Plots• The box has lines at the lower quartile, median, and upper

quartile values.

• The whiskers are lines extending from each end of the box to show the extent of the rest of the data.

• Outliers are data with values beyond the ends of the whiskers.

• If there is no data outside the whisker, a dot is placed at the bottom whisker.

1

0

1

2

3

4

5

6

7

8

9

10

Valu

es

Column Number

+

Page 55: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

55

1 2

0

5

10

15

20

Va

lue

s

Column Number

Box Plots• boxplot(X,notch) with notch = 1 produces a notched-box plot.

• Notches graph a robust estimate of the uncertainty about the means for box-to-box comparison. The default, notch = 0, produces a rectangular box plot.

Example:

>>test2 = test * (rand*10)

>>boxplot([test test2],1)

Statistics II

D. Anovas

A. 1 Way Unrelated Design

B. Post Hoc vs A Priori Comparisons

C. N-Way Anovas

D. Unrelated (Between Groups) Design

E. Related (Repeated Measures) Design

Anovas• ANOVA’s are tests used to make direct

comparisons between the amount by which

sample means vary and the amount that values

in each sample vary around the group means

1 2 3 4

-10

0

10

20

30

40

50

60

70

Va

lues

Column Number

Anovas• ANOVA’s are tests used to make direct

comparisons between the amount by which

sample means vary and the amount that values

in each sample vary around the group means

AnovasTerminology

Null Hypothesis = Both Means are the same

Type I error:

Reject Null Hypothesis when it is true. Eg Means are

not actually significantly when p < 0.05

Type II error:

Accept Null Hypothesis when it is false. Eg means

are actually significantly different when p > 0.05

Anovas

0 20 40 60 80 100

0.005

0.015

0.025

0.035

Alpha

Probability of

making type I

ErrorP < 0.05

Beta

Probability of

making type II

Error

Page 56: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

56

AnovasTerminology

Family Wise Error:

The probability of making at least 1 family wise error

while making multiple ANOVA comparisons

1 way AnovasThe matlab function anova1 calculates a 1 way anova

p = anova1(X) performs a balanced 1-way ANOVA comparing the means of the columns of data in the matrix X

** each column must represent an independent sample containing m mutually independent observations.

The function returns the p-value for the null hypothesis

p = anova1(X,group)

group = Each row of group contains the data label for the corresponding column of X

1 way Anovas

Assumptions

All sample populations are normally distributed

All sample populations have equal variance

All observations are mutually independent

The ANOVA test is known to be robust to modest violations

of the first two assumptions.

1 way Anovas

The standard ANOVA table divides the variability of the data in

X into two parts:

1. Variability due to the differences among the column means

(variability between groups)

2. Variability due to the differences between the data in each

column and the column mean (variability within groups)

1 way Anovas

The ANOVA table has six columns:

1. Source of the variability

2. The Sum of Squares (SS) due to each source.

3. The degrees of freedom (df) associated with each

source.

4. Mean Squares (MS) for each source, which is the

ratio SS/df.

5. F statistic, which is the ratio of the MS's.

6. The p-value, which is derived from the cdf of F. As F

increases, the p-value decreases.

1 way Anovas

Example 1

The following example comes from a study of the material

strength of structural beams in Hogg (1987). The vector

strength measures the deflection of a beam in

thousandths of an inch under 3,000 pounds of force.

Stronger beams deflect less. The civil engineer

performing the study wanted to determine whether the

strength of steel beams was equal to the strength of two

more expensive alloys.

Page 57: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

57

1 way AnovasExample 1

Steel is coded 'st' in the vector alloy. The other materials are

coded 'al1' and 'al2'. S

strength = [82 86 79 83 84 85 86 87 74 82 78 75 76 77 79 ...

79 77 78 82 79];

alloy = {'st','st','st','st','st','st','st','st',...

'al1','al1','al1','al1','al1','al1',...

'al2','al2','al2','al2','al2','al2'};

Though alloy is sorted in this example, you do not need to sort

the grouping variable.

1 way Anovas

Solution:

p = anova1(strength,alloy)

p =

1.5264e-004

The p-value indicates that the three alloys are significantly

different. The box plot confirms this graphically and shows that

the steel beams deflect more than the more expensive alloys.

1 way Anovas

st al1 al2

74

76

78

80

82

84

86

Valu

es

Post Hoc and A Priori Comparisons

If a 1 way anova test indicates a significant difference between at least on mean:

Post Hoc Comparisons: The decision to compare means after a significant 1 way anova is caluculated. When all possible comparisons are made after the fact the changes of type 1 error become high.

A Priori Comparisons: Comparisons decided upon before the 1 way anova is performed based on the general theory of the study. This minimizes possible type I error.

N-way AnovasUnrelated (Between Groups) Design

p = anovan(X,group) performs a balanced or unbalanced mult way ANOVA for comparing the means of the observations in vector X with respect to N different factors.

• The factors and factor levels of the observations in X are assigned by the cell array group.

• Each of the N cells in group contains a list of factor levels identifying the observations in X with respect to one of the N factors.

• The list within each cell can be a vector, character array, or cell array of strings, and must have the same number of elements as X.

Image Processing

Page 58: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

58

What Is the Image Processing

Toolbox?

• The Image Processing Toolbox is a collection of

functions that extend the capability of the MATLAB ®

numeric computing environment. The toolbox

supports a wide range of image processing

operations, including:

– Geometric operations

– Neighborhood and block operations

– Linear filtering and filter design

– Transforms

– Image analysis and enhancement

– Binary image operations

– Region of interest operations

MATLAB Image Types

• Indexed images : m-by-3 color map

• Intensity images : [0,1] or uint8

• Binary images : {0,1}

• RGB images : m-by-n-by-3

Indexed Images

» [x,map] = imread('trees.tif');

» imshow(x,map);

Intensity Images

» image =

ind2gray(x,map);

» imshow(image);

Binary Images

» imshow(edge(image));

RGB Images

Page 59: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

59

Image Display

• image - create and display image object

• imagesc - scale and display as image

• imshow - display image

• colorbar - display colorbar

• getimage- get image data from axes

• truesize - adjust display size of image

• zoom - zoom in and zoom out of 2D plot

Image Conversion

• gray2ind - intensity image to index image

• im2bw - image to binary

• im2double - image to double precision

• im2uint8 - image to 8-bit unsigned integers

• im2uint16 - image to 16-bit unsigned integers

• ind2gray - indexed image to intensity image

• mat2gray - matrix to intensity image

• rgb2gray - RGB image to grayscale

• rgb2ind - RGB image to indexed image

Creating Gui’s

GUI

• Graphical User Interface

– A tool for interacting with the computer

How is this useful?

• Visually interaction with data is often simpler

and more intuitive

• Faster manipulation of data

• Interactive

• Easy to Learn!

• Fool Proof

Some Examples

Page 60: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

60

Components of a GUI

• Front End

– point of interaction with user

• Back End

– where the action is, the code controlling the

graphics and the different widgets

Components of a GUI

• Front End

– Select and place different objects (widgets) on

the graphical layout. These will the what the

user interacts with.

– Underlying the GUI is the backend which

controls how the GUI reacts on an event.

– This is called event-driven programming

Components of a GUI

• Back End

– The code underlying the frontend graphics.

– Matlab gives a basis and you fill in the details

In Matlab

• Matlab provides interactive tool for creating the

graphics and underlying code for GUIs

– Function is called GUIDE

– Provides some templates for simple GUIs that

can be expanded as need be

• Launch GUIDE in Matlab and select on of the pre-

made templates (ie. not Blank)

GUI with Axis and Menu

• This is the layout for a simple GUI that allows you to

select one of 5 pre-made plots.

• Not very useful but a good basis to start with

• Press the Launch button and save

• You will see the screen and you can interact with it

Backend of Axis and Menu

• When you launch the GUI created the .fig file which

is the graphics and the .m file which is the

underlying code that control the widget.

– Take a Look at the .m file

– It looks like a mess, but it is not so bad!

• Lets explore this code

• First lets understand the basic m-file format

template for an empty GUI

Page 61: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

61

Common Input Arguments

All functions in the M-file have the following input arguments corresponding to the handles structure:

• hObject -- the handle to the figure or Callback object

• handles -- structure with handles and user data

The handles structure is saved at the end of each function with the command:

guidata(hObject, handles);

Functions and Callbacks in the M-File

Sharing Data with the Handles Structure

• When you run a GUI, the M-file creates a handles structure that contains all the data for GUI objects, such as controls, menus, and axes.

• The handles structure is passed as an input to each callback (user interface).

• You can use the handles structure to Share data between callbacks using the ‘guidata’ function

Functions and Callbacks in the M-File

Sharing Data

To store data that is contained in a variable X, set a field of the handles structure equal to X and then save the handles structure with the guidata function:

handles.current_data = X;guidata(hObject,handles)

You can retrieve the data in any other callback with the command:

X = handles.current_data;

Functions and Callbacks in the M-File

You can add code to the following parts of the GUI M-file:

• Opening function -- executes before the GUI becomes visible to the user.

• Output function -- outputs data to the command line, if necessary.

• Callbacks -- execute each time the user activates the corresponding component of the GUI.

Functions and Callbacks in the M-File

Opening Function

• The opening function contains code that is executed just before the GUI is made visible to the user. • You can access all the components for the GUI in the opening function, because all objects in the GUI are created before the opening function is called. • You can add code to the opening function to perform tasks that need to be done before the user has access to the GUI

This includes:

creating data, plots or images, or making the GUI blocking with the uiwait command.

Functions and Callbacks in the M-File uiwait

• The command uiwait makes the M-file halt execution

� This is useful to force the program to pause execution until a user activates a some component in the GUI.

• The uiresume command allows the M-file to resume execution once the user input is complete

Page 62: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

62

Opening Function

For a GUI whose file name is my_gui, the definition line for the opening function is:

function my_gui_OpeningFcn(hObject, eventdata, handles, varargin)

Besides the arguments hObject and handles, the opening function has the following input arguments:

• eventdata -- reserved for a future version of MATLAB • varargin -- command line arguments to untitled

Functions and Callbacks in the M-File Opening Function (varargin)

• All command line arguments are passed to the opening function via varargin. • If you open the GUI with a property name/property value pair as arguments, the GUI opens with the property set to the specified value.

For example:

my_gui('Position', [71.8 44.9 74.8 19.7])

opens the GUI at the specified position, since Position is a valid figure property

Functions and Callbacks in the M-File

Output Function

The output function returns output arguments to the command line.

GUIDE generates the following output function:

% --- Outputs from this function are returned to the command line.function varargout = my_gui_OutputFcn(hObject, eventdata, handles)% Get default command line output from handles structurevarargout{1} = handles.output;

Functions and Callbacks in the M-File

Callbacks

• When a user activates a component of the GUI, the GUI executes the corresponding callback.

• The name of the callback is determined by the component's Tag property and the type of callback.

For example, a push button with the Tag print_button executes the callback:

function print_button_Callback(hObject, eventdata, handles)

Functions and Callbacks in the M-File

Output Function

• By default the output is the handle to the GUI, which is assigned to handles.output in the opening function.

• To make the GUI return a different output (eg. return the result of a user response, such as pressing a push button):

% Add the command uiwait to the opening function % For each component of the GUI where you expect a user response, make the callback update the value of handles.output, and execute uiresume.

handles.output = ‘some response string';guidata(hObject, handles);uiresume;

Functions and Callbacks in the M-File

Property Inspector

• Adjusts the details of the different widgets

Page 63: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

63

Something Useful?

• Now, lets try and build something that we may

actually use. How about a simple program that

combines loading, plotting and calculating some

simple statistics on preformatted data

• Create a GUI that will load ‘week8_testdata2.txt’,

plot the data points as well as a linear regression

Hint, All you need are simple push buttons and an axis

for plotting

Push Buttons

• Work like independent functions

• Each button function is passed all data from the GUI handles

% --- Executes on button press in Exit.function Exit_Callback(hObject, eventdata, handles)% hObject handle to Exit (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)close gcf

• Detailed descriptions of all GUI callback controls can be found within the GUIDE help menu.

Programming GUI controls

Layout the GUIImproving Program Efficiency

Programming Efficiency

A. Data types in MatlabB. Assigning Appropriate Data Resolution

A. Downsampling from 64 bit data structures

B. Assessing Execution TimeA. tic, toc functions

C. Eliminating/Minimizing Loops

D. Compiling Code

Part A: Data types in Matlab

Page 64: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

64

Part A: Data types in Matlab

Class Example Description

int8, uint8,

int16, uint16,

int32, uint32,

int64, uint64

uint16(65000) Array of signed (int) and unsigned (uint) integers.

Some integer types require less storage space than

single or double. All integer types except for int64 and

uint64 can be used in mathematical operations.

single single(3 *

10^38)

Array of single-precision numbers. Requires less

storage space than double, but has less precision and

a smaller range.

double 3 * 10^300

5 + 6i

Array of double-precision numbers. Two- dimensional

arrays can be sparse. The default numeric type in

MATLAB.

logical magic(4) > 10 Array of logical values of 1 or 0 to represent true and

false respectively. Two-dimensional arrays can be

sparse.

char 'Hello' Array of characters. Strings are represented as vectors

of characters. For arrays containing more than one

string, it is best to use cell arrays.

Part A: Data types in Matlab

cell array a{1,1} = 12; a{1,2}

= 'Red'; a{1,3} =

magic(4);

Array of indexed cells, each capable of storing

an array of a different dimension and data

type.

structure a.day = 12;

a.color = 'Red';

a.mat = magic(3);

Array of C-like structures, each structure

having named fields capable of storing an

array of a different dimension and data type.

function handle @sin Pointer to a function. You can pass function

handles to other functions.

user class polynom([0 -2 -5]) Objects constructed from a user-defined class.

See MATLAB® Classes

Java class java.awt.Frame Objects constructed from a Java class. See

Sun™ Java™ Classes.

Part A: Assigning Appropriate

Data Resolution

• By default, numeric values are saved in

matlab as 64 bit floating point values

• Large data sets recorded experimentally

generally utilizes smaller or more specific

data resolution

• Down-sampling large datasets can

significantly save on memory and

dramatically improve execution time

Binary Precision

• The number of bits used to represent a value determines how large or small that value can be

•8 bits 0 to 256

•16 bits 0 to 65536

•32 bits 0 to 4.2950e+009

•64 bits 1.8447e+019!

•Precision also determines how many decimal places can be represented

'schar' Signed character; 8 bits

'uchar' Unsigned character; 8 bits

'int8' Integer; 8 bits

'int16' Integer; 16 bits

'int32' Integer; 32 bits

'int64' Integer; 64 bits

'uint8' Unsigned integer; 8 bits

'uint16' Unsigned integer; 16 bits

'uint32' Unsigned integer; 32 bits

'uint64' Unsigned integer; 64 bits

* The first bit denotes

the sign if the integer

or character is signed.

Numeric Formats:

Integers and Characters

Readable Binary Data Formats

Floating Point Representation

• By default matlab stores all values with double precision

• The functions realmax and realmin return max and min value representations

'float32‘, ‘single’ Floating-point; 32 bits

'float64', 'double' Floating-point; 64 bits

Page 65: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

65

Part B: Assigning Appropriate

Data Resolution

• The following functions can be used to convert

between numeric formats in matlab:

single, double, uint8, uint16, int8, int16, int32

eg. single(x) will convert matrix x to 32 bit IEEE floating

point representation

• Operations on numeric formats are defined for

matlab version 7 and later

• BE CARFUL, EXCESSIVE DOWNSAMPLING CAN

LEAD TO ROUNDING ERRORS

Part B: Assigning Appropriate

Data Resolution• Lets look at an example:

testmatrix = magic(1000);

testmatrix = single(testmatrix);

[rowdim, coldim] = size(testmatrix);

tic

for rowloop = 1:rowdim

for colloop = 1:coldim

testmatrix(rowloop,colloop) = testmatrix(rowloop,colloop) * 50;

end

end

toc

Part B: Assessing Execution

Time

• The tic and toc functions quantitatively assess

how long it takes to run any series of commands

in Matlab

• tic starts a stopwatch timer.

• toc prints the elapsed time since tic was

used.

Part C: Assessing Execution

Time

• The tic and toc functions work together to

measure elapsed time. tic saves the current time

that toc uses later to measure the elapsed time.

• The sequence of commands:tic

operations

toc

• measures the amount of time MATLAB takes to

complete one or more operations, and displays

the time in seconds.

Part C: Assessing Execution

Time

• For example, add 50 to every element of some

2D matrix

testmatrix = magic(1000);

[rowdim, coldim] = size(testmatrix);

tic

for rowloop = 1:rowdim

for colloop = 1:coldim

testmatrix(rowloop,colloop) = testmatrix(rowloop,colloop) + 50;

end

end

toc

Part C: Assessing Execution

Time

• The tic, toc functions allow for the direct

comparison of execution time when assessing

the efficiency of different programming

algorithms

Page 66: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

66

Part C: Eliminating/Simplifying

Loops

• Since Matlab is an interpreted language, certain

common programming techniques (especially for loops)

are intrinsically inefficient.

• Whenever possible, you should try to find a vector

function (or the composition of a few vector functions)

that will accomplish the same result as a for loop.

• The process of converting a for loop to vector function is

referred to as vectorization

• The difference in processing time between vectorization

and a for loop can be astounding!

For example, eliminate the for loop in the earlier example:

testmatrix = magic(1000);

[rowdim, coldim] = size(testmatrix);

tic

for rowloop = 1:rowdim

for colloop = 1:coldim

testmatrix(rowloop,colloop) = testmatrix(rowloop,colloop) + 50;

end

end

toc

Part C: Eliminating/Simplifying

Loops

For example, eliminate the for loop in the earlier

example:

testmatrix = magic(1000);

tic

testmatrix(:,:) = testmatrix(:,:) + 50;

toc

Part C: Eliminating/Simplifying

Loops

Part C: Eliminating/Simplifying

Loops

• Lets look at some other common

examples and then list some common

functions that aid in eliminating for loops

through vectorization

• Two generic algorithms in matlab are:

1. Find a subset of a matrix that satisfies a

condition, and do something to it.

2. Do something different to each column of a

matrix without a loop.

Part C: Eliminating/Simplifying

Loops

1. Find a subset of a matrix that satisfies a

condition, and do something to it.

Say you have a matrix:

M = magic(3)

and you want to negate every element greater

than 4.

Part C: Eliminating/Simplifying

Loops

Slow looping method:

[rowdim, coldim] = size(M);

for i=1:rowdim,

for j=1:coldim,

if (M(i,j) > 4),

M(i,j) = -M(i,j);

end

end

end

Page 67: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

67

Part C: Eliminating/Simplifying

Loops

Fast Vectorized Matlab Method:

ind = find(M > 4);

M(ind)=-M(ind);

Part C: Eliminating/Simplifying

Loops2. Do something different to each column of a

matrix without a loop.

In this case, let's subtract the mean from each column of the matrix M

M = rand(10,5);

V = mean(M);

Slow looping method:

for i=1:5,

M(i,:)=M(i,:)-V(i);

end

Part C: Eliminating/Simplifying

Loops

M = rand(10,5);

V = mean(M);

Fast Vectorized Matlab Method

M=M-V(ones(10,1),:);

That is, V is turned into a matrix the size of M and the

matrices are subtracted in one operation.

Part C: Eliminating/Simplifying

Loops

Handy functions that aid in avoiding for

loops through vectorization are:

find (find values that meet some criteria)

sum, prod, diff (sum, product, difference)

.* ./ (element by element matrix operations)

min, max (find min or max values)

zeros, ones (for initializing arrays)

• One other little tidbit: Avoid using []'s when they

aren't necessary.

• MATLAB has to create temporary storage for the

results of what it believes to be concatenation.

Eg:

tic; tic

for i=1:1000 for i=1:1000

a=[17]; a=17;

end end

toc toc

elapsed_time = 0.1987 elapsed_time = 0.0435

Part C: Eliminating/Simplifying

Loops

•MATLAB programs can be compiled has to create

temporary storage for the results of what it believes to

be concatenation.

Eg:

tic; tic

for i=1:1000 for i=1:1000

a=[17]; a=17;

end end

toc toc

elapsed_time = 0.1987 elapsed_time = 0.0435

Part D: Compiling Code

Page 68: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

68

Debugging Strategies

Debugging Strategies

A. General Concepts

B. Basic Bug Types

C. M-Editor Built in Debugger (M-Lint)

D. Debug Mode/Debugging Command

E. Common Coding Errors and Error Messages

Part A: General Concepts

• A bug is a program flaw. Originated when a

moth got stuck in an early computer at Harvard

University.

• Debugging code is both an art and a science

and can employ many different strategies.

• Requires practice and patience!

Part A: General Concepts

• The most important and simplest technique in debugging

is variable inspection

• Because most software bugs arise from the incorrect use

of variables, inspection of variables during program

operation is the most common debugging technique.

Part A: General Concepts

There are many ways to inspect variables:

- Omit semicolon at end of line to output results

- Use disp() function

- For larger arrays, vectors or matrices plot results

• Usually errors occur because a variable(s) contains something other

than what was intended.

• Inspection of any variable within the workspace can be accomplished at

any time during execution by setting breakpoints within an m-file

*** It can be helpful to run functions as a script to make all variables easily

available to the workspace for variable inspection

Part A: General Concepts

Error vs Warning Messages

• Matlab indicates coding issues via messages printed to the

command line before, during or after program execution.

• Warning messages are colored black and indicate potential

problems/issues and do not interfere with code execution

• Since warnings do not effect code execution, they do not have to

be fixed if they are deemed unimportant

• Errors messages are colored red and are generated when

problems are sever enough to cause program execution to abort

• Errors must be fixed in order for code to execute

Page 69: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

69

Part A: General Concepts

Error vs Warning Messages

• Unimportant warning messages can be disabled

To Disable all warning messages:Warning off

To Enable all warning messages:Warning on

To disable individual warning messages:>> 6/0Warning: Divide by zero.ans =

Inf>> warning('off','MATLAB:divideByZero')

Part A: General Concepts

The Stack

• Functions can call other functions, which in turn call other functions.

• When an error occurs, MATLAB provides an error message that

displays the "stack“ (i.e. a list of the function where the error occurred,

as well as all other parent function(s) that called that function).

• These error messages can be confusing as beginners may find it

difficult to determine where the problem actually occurred.

Part B:Basic Bug Types

There are Three Main Types of Bugs:

1. Typographic errors

2. Syntax errors

3. Algorithmic errors

Part B:Basic Bug TypesTypographic errors:

• A typo, or typographic error, is a simple typing error.

• Function name typos are usually easy to find

• Variable name typos, can be hard to find and can lead to

unexpected errors much later in your code

Example 1:

cod(pi)when you meant to type cos(pi)

??? Undefined function or variable 'cod'.

Part B:Basic Bug TypesTypographic errors:

• A typo, or typographic error, is a simple typing error.

• Function name typos are usually easy to find

• Variable name typos, can be hard to find and can lead to

unexpected errors much later in your code

Example 2:

x=cos(y);when you meant to typex=cos(t);

If ‘t’ is a different size than ‘y’, you will get an error message

about the size of the ‘x’ when you call it later in your code

Part B:Basic Bug TypesTypographic errors:

• Furthermore, if you utilize a function or variable name that is

identical to a built in function or variable in matlab (or any

installed toolbox), this can lead to errors unrelated to your code.

Avoid these mistakes by:

• Add code and data paths to top and not bottom of the matlab

search path to ensure built in function names will not be

executed first

• Use the ‘which’ function to confirm that the intended function

will be executed

Page 70: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

70

Part B:Basic Bug TypesSyntax errors:

• A syntax error results when the order, structure, or form of a function call

is incorrect

• Can occur when a function is called with inputs that are the wrong shape,

size, and/or type or are otherwise not valid

Example:

>> cos('ten')??? Undefined function or method 'cos' for input ar guments of type 'char'.

** Deciphering syntax related error messages can sometimes be difficult,

and tracking down where the problem originated can be even harder.

Part B:Basic Bug TypesAlgorithmic errors:

• An algorithmic error occurs when a program completes its execution,

but the results are unintended or unexpected.

• For example you wrote a program to add two numbers, passed it 2, 3

and received 6 as a result with no error or warning messages.

Part B:Basic Bug TypesAlgorithmic errors:

There are 2 Standard techniques for debugging algorithmic errors:

1. Compute the answer you expect to the problem by some means

other than MATLAB or by using an existing working example to

ensure the algorithmic principle is correct

2. Step through the code to verify that the algorithm computes the

correct result at each stage

** This requires a step-by-step inspection of variables at each stage of

the incorrectly executing m-file.

Part C:M-Editor Built in

Debugger (M-Lint)

What Is the M-Lint code Analyzer?

• The M-Lint code analyzer is available in Matlab Version 7 and

higher.

• M-Lint checks your code for problems and recommends

modifications to maximize performance and maintainability.

• Interface is similar to the Microsoft Word automatic spelling and

grammar checker, but with more features and power

Part C:M-Editor Built in

Debugger (M-Lint)

M-Lint can be used to report problems and recommendations in 2 ways:

1. Continuously check code in the editor while you work.

2. Create a report for an existing M-file or group of M-files.

Part C:M-Editor Built in

Debugger (M-Lint)

1. Continuously check code in the editor while you work.

• M-Lint highlights or underlines errors, warnings, and suggestions in the

body of the code and provides an overview in the right hand column

• The code analyzer updates automatically and continuously so you can

see if your changes addressed the indicated issues.

• For some issues/problems, M-Lint offers automatic code correction.

Page 71: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

71

Part C:M-Editor Built in

Debugger (M-Lint)

2. Create a report for an existing M-file or group of M-files.

• To do so, from an M-file in the Editor, select Tools > M-Lint > Show M-

Lint Report.

• After making changes, you must save the file and rerun the report to

see if your changes addressed the issues noted in M-Lint messages.

Setting Preferences:

Part C:M-Editor Built in

Debugger (M-Lint)M-Lint Message Indicators:

The M-Lint message indicator at the top right edge of the window conveys

the M-Lint messages reported for the file:

• Red means syntax errors were detected.

• Orange means warnings or opportunities for improvement were detected,

but no errors were detected.

• Green means no errors, warnings, or opportunities for improvement were

detected.

For example, when the indicator is red there is at least one error in the file.

Part C:M-Editor Built in

Debugger (M-Lint)Using the M-Lint Interface:

• Double click on orange or red lines in right column to find error location

• Right click over highlighted or underlined code for automatic correction

or ignore problem options

• Once changes are made M-Lint updates automatically, even if you do

not save the file.

• Some errors and warnings are highlighted, indicating M-Lint can

automatically fix the code.

Part D: Debug Mode

What is debug mode?

• Sometimes program bugs are not located at the line where

error/warning message was generated but was propagated from

earlier code.

• In other cases algorithmic errors may have occurred without any

outward error/warning messages ever being produced.

• In order to debug such situations the user must search step-by-

step for the problematic code using variable inspection

Part D: Debug Mode

Debug mode provides tools for pinpointing the location of erroneous

code by:

1. Allowing the user to halt execution of code at any point and examine

the state of all variables

2. Allowing line by line step-by-step execution of code

3. Enabling the examination of different workspaces in the stack from

nested functions

** MATLAB Debug mode can be used from both the m-editor and the

command line

Page 72: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

72

Part D: Debug ModeDebugging from the editor

Setting Breakpoints:

The insertion of breakpoints causes MATLAB to enter debug mode (indicated

by the K>> prompt in the command line).

When a breakpoint is encountered in the code, matlab halts execution at the

previous line and allows all variables currently in the workspace to be

examined.

Part D: Debug ModeDebugging from the editor

Setting Breakpoints:

You can set breakpoints in the editor in five different ways:

1. Clicking on the horizontal line next to the line number

2. Click on the set breakpoint button to set a breakpoint at the cursor location

3. Selecting ‘Set/Clear Breakpoints’ from the ‘Breakpoints’ pull down menu

4. Right click on any line of code

5. Press the F12 button

Part D: Debug ModeOnce in debug mode there are several options:

Part D: Debug Mode

Step:

• Step through your code one line at a time. F10 (Windows) or F6

(UNIX)

Part D: Debug Mode

Step In

• Open the first function called on the current line and step through that

function. F11 (Windows) or F7 (UNIX/Linux)

** Compiled functions will be ignored

Part D: Debug Mode

Step Out

• Return from a stepped into function without executing each of the

remaining lines in the function individually. Shift-F11 (Windows) or Shift-F7

(UNIX/Linux)

** When you step out of a function, you will still be in debug mode within

the parent function

Page 73: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

73

Part D: Debug Mode

Continue

• Once in debug mode, the Run button will continue execution until

the next breakpoint, error, or until the code is finished.

• Alternatively you can execute a section of code from the current

point to some other point (without setting a breakpoint) :

• This can be done by positioning the cursor at the point where

you want execution to end and select Go until cursor from the

Debug menu.

Part D: Debug Mode

Exit Debug Mode

• Once your error has been located and corrected this will halt

program execution and exit debug mode.

Part D: Debug ModeDebugging from the Command Line

Some useful debugging commands:

dbstop - Set breakpoint

dbclear - Remove breakpoint

dbcont - Resume execution

dbstack - List who called whom

dbstatus - List all breakpoints

dbstep - Execute one or more lines

dbquit - Quit debug mode

** These debugging commands work on functions, not scripts.

For a complete list of debugging commands type help debug

Part D: Debug Mode

dbstop in [m-file]

• Set a breakpoint on the first executable line of the [m-file].

Example: dbstop in test sets a breakpoint on the first

executable line of test.m

dbstop in [m-file] at [line number]

• Set a breakpoint in the [m-file] on line number [line number].

Example: dbstop in test at 10

Part D: Debug Mode

dbstop if error

• Set prior to running m-file.

• If an error is encountered, enter debug mode and open the m-

file in the editor at the line where the error occurred.

dbstop if warning

• Set prior to running m-file.

• If a warning is encountered, enter debug mode and open the

m-file in the editor at the line where the warning occurred.

Part D: Debug Mode

dbclear all in [m-file]

• Clear all breakpoints and stop conditions in the specified m-file.

dbclear all

• Cear all breakpoints and stop conditions in all active m-files.

Page 74: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

74

Part D: Debug Mode

dbstep

• Execute one line of code and remain in debug mode.

dbstep N

• Execute the next N lines of code (N must be a positive integer).

Part D: Debug Mode

dbstep in

• If the next line to be executed is a call to another function, open

that function in the editor and stop at the first line.

dbstep out

• Execute the rest of the lines in the current function, then return to

the calling function and stop on the line immediately after the

function call.

Part E: Common Errors and

Error Messages• Run time errors occur when MATLAB is forced to halt execution due to some

kind of typographic, syntax, or algorithmic error.

• When this occurs a red error message is printed to the command line

indicating the file and line number where the error occurred. Eg:

??? Error using ==> ones Too many input arguments.

Error in ==> /work/test.mOn line 10 ==> A = ones(n,n,n);

• The first part explains the error, the next gives the location of the error. Errors

will be listed in the order of the stack from the parent function to the child

function.

• If you are not executing a saved m-file then the error message will not give

you any file location information.

Part E: Common Errors and

Error Messages

Variable size or type mismatch

• Refers to errors in which a variable is assigned the value of a matrix

that is the wrong size (i.e. in number of rows and columns) or of the

wrong type (i.e. string versus number.)

• These are perhaps the most common of all, beyond simple errors of

command syntax.

Part E: Common Errors and

Error Messages

• Often occurs during the passing of variables to/from functions

that assume an argument will have a particular size and shape.

• If that variable that is used does not have exactly the right

dimensions, an error occurs.

Eg. If a vector of the correct length is being assigned, it may

make a difference whether the vector is passed as a row vector

versus as a column. This error can be solved by transposing

the variable (‘ operator).

Variable size or type mismatch

Part E: Common Errors and

Error Messages

>> a = zeros(5,2);>> a(3,:) = [1 2 3]??? In an assignment A(matrix,:) = B, the number of columns in A and Bmust be the same.>> a = zeros(5,2);>> a(:,1) = [1 2 3 4 5]??? In an assignment A(:,matrix) = B, the number of elements in the subscript of A and the number of columns in B must be the same.

Example:

Variable size or type mismatch

Page 75: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

75

Part E: Common Errors and

Error Messages

>> a = zeros(5,2);>> a(3,:) = [1 2 3]??? In an assignment A(matrix,:) = B, the number of columns in A and Bmust be the same.>> a = zeros(5,2);>> a(:,1) = [1 2 3 4 5]??? In an assignment A(:,matrix) = B, the number of elements in the subscript of A and the number of columns in B must be the same.

Example:

Variable size or type mismatch

• Use the debugger or MATLAB's ‘size’ command to check variable’s

dimensions

• To check the size of an variable returned by a function that is not assigned,

assign it to a temporary variable

Part E: Common Errors and

Error Messages

Argument size, number, or type mismatch

• Passing or receiving the incorrect number of arguments to a

function is another common error

Part E: Common Errors and

Error Messages

Example 1:

>> [value, index, extra] = max(randn(20,10))??? Error using ==> maxToo many output arguments.

** The ‘max’ function returns at most two arguments

Argument size, number, or type mismatch

Part E: Common Errors and

Error Messages

Example 2:

Argument size, number, or type mismatch

>> x = randn(1,5);>> y = 2*x;>> [p,s] = polyfit(x,y)

??? Input argument 'n' is undefined.Error in ==> /usr/local/matlab/toolbox/matlab/polyfun/polyfit.mOn line 57 ==> V(:,n+1) = ones(length(x),1);

** The ‘polyfit’ function fits a polynomial to (x,y) data. It requires

three arguments for x, y, and order of the polynomial

DO NOT misinterpret this message to mean that MATLAB's polyfit

function has a software bug in it!!

Part E: Common Errors and

Error Messages

Count-off-by-one and indexing errors

• A common error when using loops is to be "off by one", i.e. for the

loop counter to be in error by one when starting or stopping the loop, or

when using the loop counter to index data.

• This can result in executing a loop either one more or one less time

than intended.

• These can lead to indexing errors within loops.

• For example in C, the first element has an index of '0‘; in MATLAB the

first element has index 1.

Part E: Common Errors and

Error Messages

Count-off-by-one and indexing errors

>> for c = 0:5result(c) = 2*pi*c.^2;end??? Index into matrix is negative or zero .

• Here the programmer is interested in varying a variable from

0 through 5, and makes the mistake of using this variable as a

vector index as well:

Example 1:

Page 76: Non-Accredited Matlab Tutorial Sessions for beginner ... · 9/2/2010  · 05.10.2011 5 Using Matlab Working with Matrices c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix Using

05.10.2011

76

Part E: Common Errors and

Error Messages

Count-off-by-one and indexing errors

>> for c = 1:0.5:5result(c) = 2*pi*c.^2end

Warning: Subscript indices must be integer values.

• A non-integer parameter as a vector index will produce a warning only.

• Execution will proceed, but without correct matrix indexing. In this example,

results are only put into the result matrix every other iteration when the loop

counter c is equal to an integer.

Part E examples adapted from:http://www.ieee-uffc.org/ultrasonics/software/Matlab/Lecture8/Lecture8.htm

Example 2: