# Matlab Beginner Training Session Review Introduction to Matlab for

Document Sample

```					   Matlab Beginner Training
Session Review:
Research
Non-Accredited Matlab Tutorial Sessions for beginner
to intermediate level users

Winter Session Dates: February 13, 2007 - March 7, 2007
Session times: Tuesdays from 8:30am-10:00am, Wednesdays
from 8:30pm-10:00am
Session Locations: Humphrey Hall - Room 219

Instructors:
Robert Marino rmarino@biomed.queensu.ca

Course Website:
http://www.queensu.ca/neurosci/Matlab Training Sessions.htm
Last Semester
Weeks:
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
Intermediate Sessions

Intermediate Lectures

•Term 1 review
•Nonlinear Curve Fitting
•Statistical Tools in Matlab II
•Creating Graphic User Interfaces (GUIs)

Other possible topics:
•Writing ascii text data files
•3D plotting and animating
•Debugging Tools
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?
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

100101010
UNIX
Subject 1 143
Subject 2 982
Subject 3 87 …
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?
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:
Executing Commands
Basic Calculation Operators:
- Subtraction
* Multiplication
/ Division
^ Exponentiation
Using Matlab
Solving equations using variables
• Matlab is an expression 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
>> x = 6       >> x * y
Variable = Expression                  x=6            Ans = 12
Or                                  >> y = 2       >> x / y
Expression                             y=2            Ans = 3
>> x + y       >> x ^ y
**Variable Names are Case Sensitive!   Ans = 8        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

• 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
Exercises
Enter the following Matrices in matlab using spaces,
commas, and semicolons to separate rows and
columns:
 1 21 6
A =  5 17 9     B = 1 64 122 78 38 55
        
31 2 7 
        
D = 65

 4             8 41 166 42
 22           55 28 16 2 
C=          D=               
 16           0 0    1 12         E = a 5 x 9 matrix of 1’s
                          
160           25 65 24 19 
Exercises
Change the following elements in each matrix:

 1 76 6
6
A =  5 17 9     B = 1 76 122 78 38 55
64      0
        
31 0 7 
    2   
D = 65

 4            8     41 166    42
 22           55
76   28 16
0      2
C=          D=                     
 76 
16            0     0   1    12    E = a 5 x 9 matrix of 1’s
                             76 
160           25    65 24    19 
Matrix Operations
Indexing Matrices
A = [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
Scalar Operations
• Scalar (single value) calculations can be can performed on
matrices and arrays

Basic Calculation Operators
- Subtraction
* Multiplication
/ Division
^ Exponentiation
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]
63]          7         22]
3
3]
>>A .* D
Ans = [ 2 4
12 6]
Matrix Operations
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
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]
23
48
5 2]
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
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

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), …

>> A(x,y) = 10
A = [ 1 2 4 10
6382 ]
Control and Flow

• 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
Matlab Scripts

• Easy editing and saving of work
• Undo changes
added using the ‘%’ symbol to make make commands easier to
understand
• Saving M-files is far more memory efficient than saving a
workspace
Condition Statements

• 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 Statements
Example

A=6               B=0

if A > 3
D = [1 2 6]
A=A+1
elseif A > 2
D=D+1
A=A+2
end

What is evaluated in the code above?
Condition Statements
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 Statements
Example
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
Loops

• 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
Loops
For 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
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
While 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
Breaking 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
Functions in Matlab
• In Matlab, each function is a .m file
– It is good protocol to name your .m file the same as

• function outargs=funcname(inargs);

input              Function             output
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
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
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

Mini Assignment #1
4
t2
3.5
sin(2*pi*t)
3

2.5

2
f(t)

1.5

1

0.5

0

-0.5

-1
0   0.2   0.4   0.6   0.8       1     1.2   1.4   1.6      1.8        2
Time (ms)
Quick Assignment 1
Mini Assignment #1
4
t2
3.5
sin(2*pi*t)
3                                                                              figure
2.5                                                                              plot(t,a,'k','LineWidth',3); hold on;
2                                                                              plot(t,b,'ro')
xlabel('Time (ms)');
f(t)

1.5

1                                                                              ylabel('f(t)');
0.5                                                                              legend('t^2','sin(2*pi*t)');
0                                                                              title('Mini Assignment #1')
-0.5

-1
0   0.2   0.4   0.6   0.8       1     1.2   1.4   1.6      1.8        2
Time (ms)
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 Median
Mean: 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
336
468
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)
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
In Class Exercise 1:
• Create a function called se that calculates the
standard error of some vector supplied to the
function

Eg. se(x) should return the standard error of matrix x
Data Correlations
• Matlab can calculate statistical correlations using the
corrcoef() function

• [R,P] = corrcoef(A,B)

• Calculates a matrix of R correlation coefficiencts and P
significance values (95% confidence intervals) for
variables A and B

A     B
R=      A     AcorA BcorA
B     AcorB BcorB
Part B: Statistics Toolbox
•  The Statistics tool box contains a large array of
statistical tools.
• This lecture will concentrate on some of the
most commonly used statistics for research
1. Parametric and non-parametric comparisons
2. Curve Fitting
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
Parametric Tests - TTEST
5

Example:                                    4

3

For the data from exercise 3

Variable 1
2

1

0

-1

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

-3

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

Variable 2
>> [H,P] = ttest2(var1,var2)
H =1
P = 0.00000000000014877
Curve Fitting
• A least squares linear fit minimizes the square
of the distance between every data point and
the line of best fit

• P = robustfit(X,Y) returns the vector B of the y
intercept and slope, obtained by performing
robust linear fit
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.

12

10

8

6
Least squares
4                                            Robust

2

0

-2

1   2   3   4   5   6   7   8   9   10

```
DOCUMENT INFO
Shared By:
Categories:
Stats:
 views: 21 posted: 9/3/2010 language: English pages: 56
How are you planning on using Docstoc?