matlab beginner training session review: introduction to matlab for graduate research

56
Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

Upload: brenda-watts

Post on 19-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

Matlab Beginner Training Session Review:

Introduction to Matlab for Graduate Research

Page 2: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

Non-Accredited Matlab Tutorial Sessions for beginner to intermediate level users

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

Instructors:

Robert Marino [email protected]

Course Website:

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

Page 3: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 4: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

Intermediate Sessions

Intermediate Lectures

•Term 1 review•Loading Binary Data•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•Simulink Toolbox

Page 5: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

Why Matlab?

Common Uses for Matlab in Research• Data Acquisition• Multi-platform, Multi Format data importing • Analysis Tools (Existing,Custom)• Statistics• Graphing• Modeling

Page 6: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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 …

Page 7: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 8: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 9: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

Why Matlab?

Modeling• Models of complex dynamic system interactions

can be designed to test experimental data

Page 10: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

Understanding the Matlab Environment:

Executing CommandsBasic Calculation Operators:

+ Addition

- Subtraction

* Multiplication

/ Division

^ Exponentiation

Page 11: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

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

Page 12: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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 13: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

ExercisesEnter 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

Page 14: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

ExercisesChange 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

Page 15: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 16: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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 17: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 18: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 19: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 20: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 21: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

• 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

Page 22: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

• 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

Page 23: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 24: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

6 3 8 2 ]

Relational Operators

Page 25: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

• 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

Page 26: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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 27: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

• 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 28: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 29: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 30: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 31: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Condition Statements

Page 32: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

• 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

Page 33: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 34: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 35: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 36: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 37: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 38: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 39: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

Breaking out of loopsExample:

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

Page 40: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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 41: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 42: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

Basics• Matlab has a powerful plotting engine that can

generate a wide variety of plots.

Page 43: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 44: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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)

Page 45: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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)

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

Page 46: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 47: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

Mean and MedianMean: Average or mean value of a distributionMedian: 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.8mean(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 48: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 49: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 50: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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 BR = A AcorA BcorA B AcorB BcorB

Page 51: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 52: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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)

Page 53: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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 54: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

Parametric Tests - TTESTExample:For the data from 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

Var

iabl

e 1

Variable 2

Page 55: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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

Page 56: Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research

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.

1 2 3 4 5 6 7 8 9 10

-2

0

2

4

6

8

10

12

Least squaresRobust