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
76
Embed
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
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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
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
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
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
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]
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
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:
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
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..
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
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
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
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
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
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
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
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
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
• 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
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.
• 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
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.
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.
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
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.
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
+
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
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.
05.10.2011
57
1 way AnovasExample 1
Steel is coded 'st' in the vector alloy. The other materials are
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
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
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
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
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
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.
• 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
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
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
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
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
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
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
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.
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
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
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.
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
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:
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