Matlab for Psychologists: A Tutorial
Matlab for Psychologists: A Tutorial
Table of Contents
Table of Contents
IntroductionIntroduction ... 22 Lesson 1
Lesson 1 – The – The BasicsBasics ... 33 Lesson
Lesson 2 - 2 - Matrices and Matrices and PunctuationPunctuation ... 33 Lesson
Lesson 3 - 3 - IndexingIndexing ... 66 Lesson 4
Lesson 4 - Basic maths...- Basic maths... 77 Lesson 5 - Basic functions...
Lesson 5 - Basic functions... 88 Lesson
Lesson 6 - 6 - Logical OperLogical Operatorsators ... 99 Lesson 7
Lesson 7 - Missing - Missing DataData... 1010 Lesson 8
Lesson 8 - Basic Graphs...- Basic Graphs... 1111 Lesson
Lesson 9 - 9 - Basic ScrBasic Scriptsipts ... 1313 Lesson 10
Lesson 10 - Flow C- Flow Controlontrol... 1414 Lesson 11 - Functions...
Lesson 11 - Functions... 1616 Lesson 12 –
Lesson 12 – More about variables...More about variables... 1717 Lesson 13 -
Lesson 13 - Advanced Graphs...Advanced Graphs... 1919 Lesson 14
Lesson 14 - How do - How do I read this I read this data file into data file into Matlab?Matlab? ... 2121 Lesson 15
Lesson 15 - An exam- An example of a ple of a complete analysis complete analysis scriptscript ... 2222 Exercise
Exercise A: Data A: Data ManipulationManipulation ... 2323 Exercise B: Maths
Exercise B: Maths and functions...and functions... 2323 Exercise C:
Exercise C: Logicals...Logicals... 2424 Exercise
Exercise D: D: A A real real data data setset ... 2424 Exercise
Exercise E: BE: Basic asic GraphsGraphs ... 2525 Exercise F:
Exercise F: Scripts and Scripts and FunctionsFunctions ... 2525 Exercise G:
Exercise G: Structures and Structures and cellscells ... 2626 Exercise H:
Exercise H: More real More real datadata ... 2626 Glossary
Glossary - - DefinitionsDefinitions ... 2727 Glossary -
Glossary - Operators...Operators... 2828 Glossary
Glossary - - Basic Basic CommandsCommands ... 2929 Glossary
Glossary - Graph- Graphics funics functionsctions ... 2929 Glossary
Introduction
Introduction
Matlab is a language, and like all languages, the b
Matlab is a language, and like all languages, the best way to learn is by using it. est way to learn is by using it. This tutorialThis tutorial starts off covering the basic grammar of Matlab, and then moves on to realistic examples and lots of starts off covering the basic grammar of Matlab, and then moves on to realistic examples and lots of exercises.
exercises. It may seem slow to get started, but it really is worth pIt may seem slow to get started, but it really is worth persisting because once you knersisting because once you knowow how to use Matlab, you will be able to:
how to use Matlab, you will be able to: •
• analyze your data much quicker, more flexibly and with fewer errors than you ever could inanalyze your data much quicker, more flexibly and with fewer errors than you ever could in Excel
Excel •
• Use Cogent to carry out Use Cogent to carry out experimentsexperiments •
• Generate stimuli - pictures, Generate stimuli - pictures, sounds, movies, according to precise specificationssounds, movies, according to precise specifications •
• Write scripts for SPM so you can analyze your imaging data quickly and efficientlyWrite scripts for SPM so you can analyze your imaging data quickly and efficiently There are a couple of things to bear in min
There are a couple of things to bear in mind before you start. d before you start. There is no one right way to do anThere is no one right way to do anythingything in Matlab - lots of pieces of code may have the same effect, but as
in Matlab - lots of pieces of code may have the same effect, but as you get better it is worth lookingyou get better it is worth looking for ways to make your code neat, then it will run q
for ways to make your code neat, then it will run quickly and be easy to debug. uickly and be easy to debug. Starting from scratchStarting from scratch on any project is very intimidating and the one of the best way's to start on Matlab is to take scripts on any project is very intimidating and the one of the best way's to start on Matlab is to take scripts that other people have written and adapt them to what yo
that other people have written and adapt them to what you need. u need. Some of the scripts in this tutorialSome of the scripts in this tutorial may help, or ask people for
may help, or ask people for their scripts (especially for SPM and their scripts (especially for SPM and Cogent).Cogent).
Getting started
Getting started
These notes assume that the reader
These notes assume that the reader uses Windows and has no prouses Windows and has no programming experience. gramming experience. Linux / UnixLinux / Unix users and people with experience of C - please be patient.
users and people with experience of C - please be patient.
Before you start, you should know that Matlab hates file names with spaces in (and so do I), so if you Before you start, you should know that Matlab hates file names with spaces in (and so do I), so if you are going to use Matlab extensively, get used to using _ (underscore) instead of space in your file and are going to use Matlab extensively, get used to using _ (underscore) instead of space in your file and directory names, and avoid keeping important files in the 'My Documents' folder or the Desktop in directory names, and avoid keeping important files in the 'My Documents' folder or the Desktop in Windows.
Windows. Make a folder directly in C: or D: or whatever and uMake a folder directly in C: or D: or whatever and use that for your Matlab analysis – itse that for your Matlab analysis – it will make your life much easier.
will make your life much easier.
Start Matlab by clicking on the icon on you
Start Matlab by clicking on the icon on your desktop, and a variety of windows r desktop, and a variety of windows will open up. will open up. TheThe main blank window is the
main blank window is the command windowcommand window, which has a, which has a promptprompt
>>
>>
where you type your instructionswhere you type your instructions to Matlab.to Matlab. I find it best to close all the other windoI find it best to close all the other windows, except maybe thews, except maybe the command historycommand historywindow, aswindow, as the rest are a bit useless.
the rest are a bit useless.
The current directory is shown at the top of the command window, and you can change directories by The current directory is shown at the top of the command window, and you can change directories by clicking on the three dots to the right of it.
clicking on the three dots to the right of it. You can also use the system You can also use the system commandscommands
ls
ls
,,cd
cd
,,dir
dir
andandpwd
pwd
to move between directories.to move between directories.As you read though this tutorial, try typing each line into Matlab, and if you don't understand what it is As you read though this tutorial, try typing each line into Matlab, and if you don't understand what it is doing, try something else until you do.
doing, try something else until you do. The only way to learn Matlab is by using it, sThe only way to learn Matlab is by using it, so just try stuff.o just try stuff. Though out this tutorial, things you can type into Matlab are show in
Though out this tutorial, things you can type into Matlab are show in
green
green
and Matlab's response isand Matlab's response is shown inshown in
blue
blue
. . Words Words highlighted highlighted inin redredare (in general) defined in the glossary at the end.are (in general) defined in the glossary at the end.Getting help
Getting help
Matlab has a detailed help section, which you can access by clicking on the question mark at the top of Matlab has a detailed help section, which you can access by clicking on the question mark at the top of the command window and
the command window and searching. searching. At any time, you At any time, you can typecan type
help
help
to get a list of categories of to get a list of categories of commands, for example typecommands, for example type
help general
help general
for a list of general cofor a list of general commands. mmands. TypeTypehelp
help
followedfollowed by a command nameby a command name to get more help to get more help on that command. on that command. For example:For example:
>>
>> help length
help length
LENGTH
LENGTH
Length
Length
of
of
vector.
vector.
LENGTH(X) returns
LENGTH(X) returns
the length
the length
of vector
of vector
X.
X.
It is
It is
equivalent to
equivalent to
MAX(SIZE(X)) for non-empty arrays and 0 for empty ones.
Lesson 1 – The Basics
Lesson 1 – The Basics
Matlab is based on a command line where you can see and manipulate
Matlab is based on a command line where you can see and manipulate variablesvariables. . You You enterenter commands at the prompt
commands at the prompt
>>
>>
and Matlab responds.and Matlab responds.To create the variable A with the value 1 (N.B. spaces before and after = are optional). To create the variable A with the value 1 (N.B. spaces before and after = are optional).
>>
>> A=10
A=10
A = 10
A = 10
A is now stored as a variable in Matlab's memory or
A is now stored as a variable in Matlab's memory or workspaceworkspacewith the value with the value 10. 10. It can be It can be used inused in sums etc sums etc
>>
>> A+A
A+A
ans = 20
ans = 20
You can also put the result of a sum straight into a variable You can also put the result of a sum straight into a variable
>>
>> B = 5+8
B = 5+8
B = 13
B = 13
If you put a semi-colon at the end of the line, Matlab won’t show you the output of that command, but If you put a semi-colon at the end of the line, Matlab won’t show you the output of that command, but the value of the variable has still been changed.
the value of the variable has still been changed. >>
>>
A = 15;
A = 15;
Now type the name of the variable to see its new value: Now type the name of the variable to see its new value: >>
>>
A = 15
A = 15
The
The name of a variablename of a variablemust begin with a letter, but can have numbmust begin with a letter, but can have numbers later in the name. ers later in the name. Names areNames are case-sensitive, and can be up to 32 characters long, but cannot have spaces or punctuation in the name. case-sensitive, and can be up to 32 characters long, but cannot have spaces or punctuation in the name. You can use underscore
You can use underscore if you want a space, and there are certain reserved words likeif you want a space, and there are certain reserved words like
if
if
whichwhich cannot be used as variable namescannot be used as variable names. . If you use a command name as a variabIf you use a command name as a variable name, that command mayle name, that command may not work and you will have to clear your variable to use the command
not work and you will have to clear your variable to use the command To get rid of a variable, type
To get rid of a variable, type
clear
clear
followed by the name:followed by the name:>>
>> clear B
clear B
You can clear everything in the workspace by typing
You can clear everything in the workspace by typing
clear all
clear all
The commandThe command
whos
whos
shows you the shows you the variables that are in variables that are in the workspace. the workspace. You will see:You will see: NameName: : the name you uthe name you use to refer to se to refer to the variablethe variable Size
Size: : the number of rothe number of rows (first number) ws (first number) and columns (secoand columns (second number)nd number) Bytes
Bytes: how much memory the variable uses, but you don’t need to know that unless you are using very: how much memory the variable uses, but you don’t need to know that unless you are using very big variables.
big variables. Type
Type: all numbers are double arrays, but you can also use: all numbers are double arrays, but you can also use texttext,, cellcellandand logicallogical(see later)(see later)
>>
>> whos
whos
Name
Name
Size
Size
Bytes
Bytes
Class
Class
A
A
1x1
1x1
8
8
double
double
array
array
ans
ans
1x1
1x1
8
8
double
double
array
array
Grand total is 2 elements using 16 bytes
Grand total is 2 elements using 16 bytes
You can clear the v
You can clear the variables you have ariables you have created with the command created with the command clear. clear. UseUse
clear var
clear var
to removeto remove just the variable var or usejust the variable var or use
clear all
clear all
to clear everythingto clear everything>>
>> clear all
clear all
Lesson 2 - Matrices and Punctuation
Lesson 2 - Matrices and Punctuation
If you are familiar with Excel, you will be used to the idea of putting all your data into a grid, and then If you are familiar with Excel, you will be used to the idea of putting all your data into a grid, and then adding up the rows or colum
you like, of any size, and each one is
you like, of any size, and each one is a variable with a name. a variable with a name. You can then use the variable name toYou can then use the variable name to refer to the array when you want to man
refer to the array when you want to manipulate it. ipulate it. Some types of array are:Some types of array are: Scalar
Scalar– a single number– a single number
A = 10
A = 10
VectorVector– a row or column of numbers– a row or column of numbers
B = 1 2 3
B = 1 2 3
C = 4
C = 4
Matrix
Matrix– an array of numbers in – an array of numbers in a grid, its size is the number of rows a grid, its size is the number of rows x the number of columns. x the number of columns. D is aD is a 3 by 4 matrix. 3 by 4 matrix.
D = 5 6 7 9
D = 5 6 7 9
8 3 5 3
8 3 5 3
5 6 3 2
5 6 3 2
ElementElement– a single number within a matrix or vector.– a single number within a matrix or vector.
Brackets
Brackets
To enter most data into matlab, you need to use
To enter most data into matlab, you need to use square brackets [ ]square brackets [ ]
To put data into a
To put data into a row vectorrow vector, type the values within square brackets, separated by spaces OR commas, type the values within square brackets, separated by spaces OR commas (or both). (or both).
>>
>> C = [6, 5, 8, 10]
C = [6, 5, 8, 10]
C = 6 5 8 10
C = 6 5 8 10
To put data into a
To put data into a column vectorcolumn vector, type the values in square brackets, type the values in square brackets, separated by semi colons. , separated by semi colons. In thisIn this context, semi-colon means 'start a new line'.
context, semi-colon means 'start a new line'.
>>
>> D = [3; 1; 6; 5]
D = [3; 1; 6; 5]
D = 3
D = 3
To put data into a matrix, use commas f
To put data into a matrix, use commas for the rows and then a semi-colon to sor the rows and then a semi-colon to start each new line. tart each new line. It isIt is just like doing a row and column vector at once.
just like doing a row and column vector at once.
>>
>> E = [1, 2, 3; 4, 5, 6]
E = [1, 2, 3; 4, 5, 6]
E = 1 2 3
E = 1 2 3
4 5 6
4 5 6
In general, square brackets are u
In general, square brackets are used any time that you want to join things together. sed any time that you want to join things together. SeeSee
vertcat
vertcat
andandhorzcat
horzcat
for more information.for more information. UseUse round brackets ( )round brackets ( ) to get things out of a matrix or to refer to justo get things out of a matrix or to refer to just part of a matrix. t part of a matrix. For example,For example, E(2,3)
E(2,3) means the value in means the value in row 2, column row 2, column 3 of E3 of E
>>
>> E(2,3)
E(2,3)
ans = 6
ans = 6
If you try to refer to something outside E, you will get an error message If you try to refer to something outside E, you will get an error message
>>
>> E(4,3)
E(4,3)
???
You can also use round brackets
You can also use round brackets to change part of a matrix. to change part of a matrix. To make the number in the 1To make the number in the 1ststrow and 3row and 3rdrd column of E be 10, type column of E be 10, type
>>
>> E(1,3) = 10
E(1,3) = 10
E
E
=
=
1
1
2
2
10
10
4
4
5
5
And if you want to add a row or column to a matrix, you just need to refer to it and it will be created. And if you want to add a row or column to a matrix, you just need to refer to it and it will be created. Note that this only works if you are adding a row or column of the same size as your original matrix, if Note that this only works if you are adding a row or column of the same size as your original matrix, if you try adding a different size, you will get an error message.
you try adding a different size, you will get an error message.
>>
>> E(3,:) = [7, 8, 9]
E(3,:) = [7, 8, 9]
E
E
=
=
1
1
2
2
10
10
4
4
5
5
7
7
8
8
Colon
Colon
TheThe coloncoloncharactercharacter means several different things in Matlab.means several different things in Matlab.
In round brackets, a colon means everything in a row or column and is normally used to extract data In round brackets, a colon means everything in a row or column and is normally used to extract data from a matrix.
from a matrix.
E(:,2) means everything in column 2 of
E(:,2) means everything in column 2 of E. E. Read this as 'E, every row, column Read this as 'E, every row, column 2'2'
>>
>> E(:,2)
E(:,2)
ans = 2
ans = 2
E(2,:) means every column in row 2
E(2,:) means every column in row 2 of E. of E. Read this as 'E, row 2, every columRead this as 'E, row 2, every column'n'
>>
>> E(2,:)
E(2,:)
ans = 4 5 6
ans = 4 5 6
A colon in brackets by itself turns an
A colon in brackets by itself turns anything into a column vector. ything into a column vector. E(:) rearranges everything in E intoE(:) rearranges everything in E into one long column
one long column
>>
>> E(:)
E(:)
ans = 1
ans = 1
10
10
Between two numbers, the colon means count from A to B one integer at a time Between two numbers, the colon means count from A to B one integer at a time
>>
>> F = 5:10
F = 5:10
F = 5 6 7 8 9 10
F = 5 6 7 8 9 10
You can use a colon like this to extract data from
You can use a colon like this to extract data from a matrix too. a matrix too. For example, F(:,3:5) mFor example, F(:,3:5) meanseans everything in columns 3, 4 and 5 of F
everything in columns 3, 4 and 5 of F
>>
>> F(:,3:5)
F(:,3:5)
ans = 7 8 9
A set of three numbers with a colon specifies the step to use for counting, e.g. G = 3:4:20 means G A set of three numbers with a colon specifies the step to use for counting, e.g. G = 3:4:20 means G counts from 3 to 20 in steps of 4
counts from 3 to 20 in steps of 4
>>
>> G = 3:4:20
G = 3:4:20
ans = 3 7 11 15 19
ans = 3 7 11 15 19
Type
Type
help punct
help punct
,,help colon
help colon
andandhelp paren
help paren
for more information on matrix punctuationfor more information on matrix punctuation in matlab.in matlab.
The Array Editor
The Array Editor
I never use the array editor in Matlab, but when you are making the transition from Excel, you may I never use the array editor in Matlab, but when you are making the transition from Excel, you may find it helpful.
find it helpful. Use the menus to select View - Workspace anUse the menus to select View - Workspace and Matlab will show you a window listingd Matlab will show you a window listing all your variables and their sizes, s
all your variables and their sizes, similar to typing whos. imilar to typing whos. Then if you click on a variable, theThen if you click on a variable, the ArrayArray
Editor
Editorwindow opens. window opens. This shows you the data in a gThis shows you the data in a grid a bit like Excel, and any numbers you changrid a bit like Excel, and any numbers you changee here will be changed in Matlab's memory, while commands at the command prompt which change the here will be changed in Matlab's memory, while commands at the command prompt which change the variable you are looking at will automatically be shown in th
variable you are looking at will automatically be shown in the array editor. e array editor. You can also paste dataYou can also paste data from another program (like Excel) into a Matlab variable here.
from another program (like Excel) into a Matlab variable here.
Lesson 3 - Indexing
Lesson 3 - Indexing
Indexing means getting the part of a ma
Indexing means getting the part of a matrix you want, and it is crucial to Matlab. trix you want, and it is crucial to Matlab. The easiest way toThe easiest way to get the data you want is to use
get the data you want is to use subscriptssubscripts, i.e. to tell Matlab the rows and columns that you want., i.e. to tell Matlab the rows and columns that you want. For this example, we will use a magic square matrix which is stored in Matlab and accessed with the For this example, we will use a magic square matrix which is stored in Matlab and accessed with the command magic.
command magic.
>>
>> clear all
clear all
>>
>> A = magic(5)
A = magic(5)
A
A
=
=
17 24
17 24
1
1
8 15
8 15
23
23
5
5
7
7
14
14
16
16
4
4
6
6
13
13
20
20
22
22
10
10
12
12
19
19
21
21
11
11
18
18
25
25
2
2
We can extract the value in row 4 column 3 from A, using round brackets We can extract the value in row 4 column 3 from A, using round brackets
>>
>> B = A(4,3)
B = A(4,3)
B = 19
B = 19
or just row 4, read this as C is A, row 4 all columns or just row 4, read this as C is A, row 4 all columns
>>
>> C = A(4,:)
C = A(4,:)
C = 10 12 19 21 3
C = 10 12 19 21 3
We can extract rows
We can extract rows 2 and 3 from 2 and 3 from A. A. Read this as B Read this as B is A, rows 2 is A, rows 2 and 3, all columand 3, all columns. ns. The squareThe square brackets and semi-colon are used to join the required rows together and the round brackets to extract brackets and semi-colon are used to join the required rows together and the round brackets to extract the rows from A.
the rows from A.
>>
>> D = A([2;3],:)
D = A([2;3],:)
D
D
=
=
23
23
5
5
7
7
14
14
16
16
4
4
6
6
13
13
20
20
22
22
And we can extract columns 1 to 3 of D. Read this as E is D, all rows from columns 1 through 3 And we can extract columns 1 to 3 of D. Read this as E is D, all rows from columns 1 through 3
>>
>> E = D(:,1:3)
E = D(:,1:3)
E
E
=
=
23
23
5
5
4
4
6
6
13
13
We can also use indexing to put values into A, e.g. to make row 2 column 2 of A equal 100, use: We can also use indexing to put values into A, e.g. to make row 2 column 2 of A equal 100, use:
>>
>> A(2,2) = 100
A(2,2) = 100
A
A
=
=
17 24
17 24
1
1
8 15
8 15
23
23
100
100
7 14 16
7 14 16
4
4
6
6
13
13
20
20
22
22
10
10
12
12
19
19
21
21
11
11
18
18
25
25
2
2
To make all of column 4 of A equal 0, To make all of column 4 of A equal 0, useuse
>>
>> A(:,4) = 0
A(:,4) = 0
A
A
=
=
17 24
17 24
1
1
0 15
0 15
23
23
100
100
7
7
0
0
16
16
4
4
6
6
13
13
0
0
22
22
10
10
12
12
19
19
0
0
11
11
18
18
25
25
0
0
You should now know enough to do Exercise A
You should now know enough to do Exercise A
Lesson 4 - Basic maths
Lesson 4 - Basic maths
Type
Type
clear all
clear all
before starting this section, and enter enter E = [1, 2, 3; 4, 5, 6] and A=10.before starting this section, and enter enter E = [1, 2, 3; 4, 5, 6] and A=10. In matlab, you can do sums oIn matlab, you can do sums on numbers or on variables. n numbers or on variables. Variables are treated just like the number (orVariables are treated just like the number (or numbers) they repr
numbers) they represent. esent. Most things arMost things are as you would exe as you would expect:pect: +
+ means means plusplus -
- means means minusminus
' ' means transpose (means transpose (turn rows into coturn rows into columns and vice vlumns and vice versa)ersa)
( ) round brackets can be used to specify the order of operations according to BODMAS ( ) round brackets can be used to specify the order of operations according to BODMAS BUT
BUT
* means matrix multiplication * means matrix multiplication / means matrix division
/ means matrix division
You are more likely to want to dot-multiple and
You are more likely to want to dot-multiple and dot-dividedot-divide .* means element-wise multiplication
.* means element-wise multiplication ./ means element-wise division
./ means element-wise division
.^ means power (i.e. A.^2 means A squared) .^ means power (i.e. A.^2 means A squared) You can do su
You can do sums on single nums on single numbers just by tmbers just by typing in the command yping in the command line. line. Spaces before aSpaces before and after thend after the signs are optional.
signs are optional.
>>
>> 174 .* 734
174 .* 734
ans
ans
=
=
127716
127716
>>
>> (A*2) / 5
(A*2) / 5
ans = 4
ans = 4
You can also do sums between a scalar an
You can also do sums between a scalar and a matrix. d a matrix. The sum will be applied to every value of theThe sum will be applied to every value of the matrix. matrix.
>>
>> J = E*A
J = E*A
J
J
=
=
10
10
20
20
30
30
40
50
60
40
50
60
You can add and subtract matrices if they are the same size: You can add and subtract matrices if they are the same size:
>>
>> K = J – E
K = J – E
ans
ans
=
=
9
9
18
18
27
27
36
45
54
36
45
54
You can multiple or divide elements of two matrices using
You can multiple or divide elements of two matrices using
.*
.*
andand./
./
The matrices must both be of The matrices must both be of the same size, otherwise you will get an error message.the same size, otherwise you will get an error message.
>>
>> L = [3 2 1; 9 5 6]
L = [3 2 1; 9 5 6]
L
L
=
=
3
3
2
2
9
9
5
5
To divide each value of K by the value in the equivalent place from L: To divide each value of K by the value in the equivalent place from L:
>>
>> K./L
K./L
ans
ans
=
=
3
3
9
9
27
27
4
4
9
9
To multiply each value of E by the value in the equivalent place from L: To multiply each value of E by the value in the equivalent place from L:
>>
>> E.*L
E.*L
ans =
ans =
3
3
4
4
36
25
36
36
25
36
Note that using
Note that using andand without thewithout the will perform matrix multiplication and division, where wholewill perform matrix multiplication and division, where whole rows and columns are multiplied and sum
rows and columns are multiplied and summed. med. This is described in linear algebra text bookThis is described in linear algebra text books, but yous, but you are unlikely to need it for basic data analysis.
are unlikely to need it for basic data analysis. If you multiply and you get bIf you multiply and you get back a matrix of a differentack a matrix of a different shape, you’ve probably don
shape, you’ve probably done matrix multiplication. e matrix multiplication. If your matrix is square (hIf your matrix is square (has the same number of as the same number of rows and columns), be extra careful because matrix multiplication won't produce an obvious error. rows and columns), be extra careful because matrix multiplication won't produce an obvious error. Type
Type
help elfun
help elfun
(elementary functions)(elementary functions)help ops
help ops
(operators) or(operators) orhelp arith
help arith
(arithmetic) for(arithmetic) for more information on basic maths with Matlab.more information on basic maths with Matlab.
Lesson 5 - Basic functions
Lesson 5 - Basic functions
Matlab has a large number of build in
Matlab has a large number of build in functionsfunctionswhich allow you to perform simple maths and towhich allow you to perform simple maths and to generate matrices quickly and easily.
generate matrices quickly and easily. Functions are bits of codFunctions are bits of code (written by you or Matlab or anyone)e (written by you or Matlab or anyone) which receive some inputs and give you s
which receive some inputs and give you some outputs. ome outputs. They use round brackets, anThey use round brackets, and all functionsd all functions written by Matlab have
written by Matlab have help files to tell help files to tell you how to uyou how to use them. se them. TypeType
help
help
followed by the commandfollowed by the command name for details.name for details.
All functions have one or more inputs or
All functions have one or more inputs or argumentsargumentsand produce one and produce one or more outputs. or more outputs. If a functionIf a function has just one output, the output can be placed straight into a variable, but if a function has several has just one output, the output can be placed straight into a variable, but if a function has several outputs, square brackets are needed to
outputs, square brackets are needed to group the output variables.group the output variables. All functions have the form:
All functions have the form:
[output1, output2, ...] = function (arg1, arg2, ...)
[output1, output2, ...] = function (arg1, arg2, ...)
All the mathematical functions you need to operate on single values are available, e.g
All the mathematical functions you need to operate on single values are available, e.g sinsin,, coscos,, tantan,, sqrt
sqrt,, loglogandand pipi. . Matlab has a variety of useful funMatlab has a variety of useful functions which you can apply to the rows or ctions which you can apply to the rows or columnscolumns of a matrix, including
of a matrix, including sumsum,, meanmean,, stdstd,, maxmaxandand min.min.
By default, these work on columns
By default, these work on columns, but you can change the dimension to work , but you can change the dimension to work on rows. on rows. TypeType
help
help
followed by the function name to see how to do this.followed by the function name to see how to do this. To sum the columns of K:
To sum the columns of K:
>>
>> sum(K)
sum(K)
ans
ans
= 45
= 45
63
63
81
81
To sum the rows of K, you must tell the sum function to operate in the 2nd dimension (1st = columns, To sum the rows of K, you must tell the sum function to operate in the 2nd dimension (1st = columns, 2nd = rows) 2nd = rows)
>>
>> sum(K,2)
sum(K,2)
ans
ans
=
=
54
54
135
135
To find the mean of J and put it in a variable To find the mean of J and put it in a variable
>>
>> mj = mean(J)
mj = mean(J)
mj
mj
=
=
25
25
35
35
45
45
The apostrophe is useful to
The apostrophe is useful to transposetransposea matrix or vector, i.e. to turn all the rows into columns and thea matrix or vector, i.e. to turn all the rows into columns and the columns into rows
columns into rows
>>
>> K'
K'
ans
ans
=
=
9
9
36
36
18
45
18
45
27
54
27
54
There are also a set of functions to create vecto
There are also a set of functions to create vectors and matrices. rs and matrices. These includeThese include
rand
rand
,,ones
ones
,,zeros
zeros
,,repmat
repmat
,,ndgrid, linspace, logspace
ndgrid, linspace, logspace
andandmagic
magic
..e.g. To create a matrix of random numbers with 3 rows and 5 columns (yours will be different because e.g. To create a matrix of random numbers with 3 rows and 5 columns (yours will be different because R is random) R is random)
>>
>> R = rand(3,5)
R = rand(3,5)
R =
R =
0.6154
0.7382
0.9355
0.8936
0.8132
0.6154
0.7382
0.9355
0.8936
0.8132
0.7919
0.1763
0.9169
0.0579
0.0099
0.7919
0.1763
0.9169
0.0579
0.0099
0.9218
0.4057
0.4103
0.3529
0.1389
0.9218
0.4057
0.4103
0.3529
0.1389
Many more useful functions
Many more useful functions are listed in the glossary. are listed in the glossary. type help followed by a function name to findtype help followed by a function name to find out what each one does.
out what each one does.
You should now know enough to do Exercise B.
You should now know enough to do Exercise B.
Lesson 6 - Logical Operators
Lesson 6 - Logical Operators
Type
Type
clear all
clear all
before starting this section to clear all the previous variables.before starting this section to clear all the previous variables. Logical operators are used to assLogical operators are used to assess if a statement is true or false. ess if a statement is true or false. False is always represented by 0,False is always represented by 0, and Matlab will consider any non-zero v
and Matlab will consider any non-zero value to be true. alue to be true. For neatness, it is best to uFor neatness, it is best to use 1 as true.se 1 as true. Logicals can be used to decide which part of a script to run next or which elements of a matrix to use Logicals can be used to decide which part of a script to run next or which elements of a matrix to use in a calculation.
in a calculation. There are fouThere are four main logr main logical operators:ical operators:
>
>
Greater
Greater
than
than
<
<
Less
Less
than
than
==
==
Is
Is
equal
equal
to
to
~=
~=
Is
Is
not
not
equal
equal
to
to
You can also join logicals together using AND, OR and NOT, together wit
You can also join logicals together using AND, OR and NOT, together wit h round bracketsh round brackets
&
&
logical
logical
AND
AND
|
|
logical
logical
OR
OR
~
~
logical
logical
NOT
NOT
In Matlab, you can apply logical operators to whole arrays as well as to i
In Matlab, you can apply logical operators to whole arrays as well as to i ndividual numbers, and thenndividual numbers, and then you obtain a logical array which can be used to
you obtain a logical array which can be used to indexindex another array.another array.
In this example, B shows which values of A are larger than 2, and C shows which values of A are In this example, B shows which values of A are larger than 2, and C shows which values of A are smaller than 5. smaller than 5.
>>
>> A = [1 5 3 4 8 3];
A = [1 5 3 4 8 3];
>>
>> B = A>2
B = A>2
B = 0 1 1 1 1 1
B = 0 1 1 1 1 1
>>
>> C = A<5
C = A<5
C = 1 0 1 1 0 1
C = 1 0 1 1 0 1
D shows where both B and C are true. D shows where both B and C are true.
>>
>> D = B & C
D = B & C
D = 0 0 1 1 0 1
D = 0 0 1 1 0 1
You can see that B, C and D are a logical when you type
You can see that B, C and D are a logical when you type
whos
whos
and the class is listed asand the class is listed as logicallogical. This. This means Matlab will treat these matrices as a list ofmeans Matlab will treat these matrices as a list of TrueTrueandand FalseFalsevalues rather than just a list of onesvalues rather than just a list of ones and zeroes.
and zeroes.
Now you can use D as a logical index into A: Now you can use D as a logical index into A:
>>
>> E = A(D)
E = A(D)
E = 3 4 3
E = 3 4 3
E contains only the values of A which are true according to D, that is, only the values which are larger E contains only the values of A which are true according to D, that is, only the values which are larger than 2 AND smaller than 5.
than 2 AND smaller than 5. For these values, there was a oFor these values, there was a one (TRUE) in the corresponding pne (TRUE) in the corresponding place inlace in D, and all the other values in A are dropped.
D, and all the other values in A are dropped. Logical indices can often be used in a s
Logical indices can often be used in a similar to the subscript indices described abovimilar to the subscript indices described above. e. Both functionBoth function to select out particular values from an array.
to select out particular values from an array. You can convert a logical index into a subsYou can convert a logical index into a subscript indexcript index using
using findfind, which tells you the non-zeros values of the logical., which tells you the non-zeros values of the logical.
>>
>> F = find(D)
F = find(D)
F = 3 4 6
F = 3 4 6
This means that the 3
This means that the 3rdrd, 4, 4ththand 6and 6ththvalues of D are not zero. values of D are not zero. If you use the subscript index If you use the subscript index F into A,F into A, you will get the same result as using the logical index D into A:
you will get the same result as using the logical index D into A:
>>
>> A(F)
A(F)
ans = 3 4 3
ans = 3 4 3
Logical indexing is most useful when one variable is used to categorise another. Imagine you have Logical indexing is most useful when one variable is used to categorise another. Imagine you have some data which falls into three different categories.
some data which falls into three different categories.
>>
>> data
data
=
=
[4
[4
14
14
6
6
11
11
3
3
14
14
8
8
17
17
17
17
12
12
10
10
18];
18];
>>
>> cat
cat
= [1
= [1
3 2
3 2
1 2
1 2
2 3
2 3
1 3
1 3
2 3
2 3
1];
1];
To find where cat is 2:To find where cat is 2:
>>
>> cat2 = cat==2
cat2 = cat==2
cat2
cat2
=
=
0
0
0
0
1
1
0
0
1
1
1
1
0
0
0
0
0
0
1
1
0
0
To find the values of data where cat is 2: To find the values of data where cat is 2:
>>
>> data2 = data(cat2);
data2 = data(cat2);
data2
data2
=
=
6
6
3
3
14
14
12
12
Now we can find the mean of the data for category 2 Now we can find the mean of the data for category 2
>>
>> mdat2 = mean(data2)
mdat2 = mean(data2)
mdat2 = 8.75
mdat2 = 8.75
We could have done all 3 steps in one line: We could have done all 3 steps in one line:
>>
>> mdat2 = mean(data(cat==2))
mdat2 = mean(data(cat==2))
mdat2 = 8.75
mdat2 = 8.75
Lesson 7 - Missing Data
Lesson 7 - Missing Data
Real life psychology experiments often suffer from missing data - you may want to exclude trials Real life psychology experiments often suffer from missing data - you may want to exclude trials where reaction times fall outside some limits, or wher
where reaction times fall outside some limits, or where the subject made an error. e the subject made an error. In Matlab, you canIn Matlab, you can do this using
do this using
NaN
NaN
. . NaN NaN stands stands forfor Not A NumberNot A Numberand can be used in any vector or matrix in place of and can be used in any vector or matrix in place of missing data.missing data. In general, it is In general, it is much better to repmuch better to replace your missing lace your missing data with NaNs than to data with NaNs than to delete itdelete it altogether.
you expect, but Matlab provides alternate
you expect, but Matlab provides alternate versions,versions,
nansum
nansum
,,nanmean
nanmean
andandnanstd
nanstd
which let youwhich let you ignore NaNs and find the sum, mean and standard deviation of your data.ignore NaNs and find the sum, mean and standard deviation of your data. A quick example using the data set from
A quick example using the data set from Lesson 6.Lesson 6. An additional vector err has a one at everyAn additional vector err has a one at every location where the subject made an error;
location where the subject made an error;
>>
>> err
err
=
=
[1
[1
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
0
1
1
0
0
0];
0];
We can use err as an index to replace evWe can use err as an index to replace every error in the data with a NaN. ery error in the data with a NaN. This line should be read asThis line should be read as the data where err is one is changed to NaN;
the data where err is one is changed to NaN;
>>
>> data(err==1) = NaN
data(err==1) = NaN
data
data
=
=
[NaN
[NaN
14
14
6
6
11
11
3
3
14
14
8
8
NaN
NaN
17
17
NaN
NaN
10
10
18]
18]
Now when we extract the data in category 2, one of the numbers is NaN Now when we extract the data in category 2, one of the numbers is NaN
>>
>> data2 = data(cat2);
data2 = data(cat2);
data2
data2
=
=
6
6
3
3
14
14
NaN
NaN
So we have to use nanmean to find the mean So we have to use nanmean to find the mean
>>
>> mdat2 = nanmean(data2)
mdat2 = nanmean(data2)
mdat2 = 7.6667
mdat2 = 7.6667
Some other useful functions to use with NaNs include
Some other useful functions to use with NaNs include
isnan
isnan
, which returns a 1 at places where a, which returns a 1 at places where a matrix is a NaN and zero elsewhere, andmatrix is a NaN and zero elsewhere, and
isfinite
isfinite
, which returns a 1 at places where a matrix is a, which returns a 1 at places where a matrix is a number (not NaN or Inf) and zero elsewhere.number (not NaN or Inf) and zero elsewhere.
You should now know enough to do Exercise C and D
You should now know enough to do Exercise C and D
Lesson 8 - Basic Graphs
Lesson 8 - Basic Graphs
Visualising your data is very important, but fir
Visualising your data is very important, but first we need to generate some data. st we need to generate some data. TypeType
clear all
clear all
before you begin this section.before you begin this section. Linspace is a useful function for gLinspace is a useful function for generating a sequence of numbers oenerating a sequence of numbers of af a specific length.
specific length. Type help linspace Type help linspace to see what it doesto see what it does
>>
>> x = linspace(0,2*pi,30);
x = linspace(0,2*pi,30);
>>
>> y = sin(x);
y = sin(x);
>>
>> z = 0.5+cos(x/2);
z = 0.5+cos(x/2);
Basic graphs
Basic graphs
PlotPlotis the basic function for plotting is the basic function for plotting vectors and matrixes as lines or poinvectors and matrixes as lines or points. ts. You specify the x data,You specify the x data, the y data
the y data and the type and the type of line. of line. TypeType
help plot
help plot
for a list of for a list of possible lines. possible lines. First we will plot First we will plot yy against xagainst x
>>
>> plot(x,y,'b-o')
plot(x,y,'b-o')
A new window called Figure 1 will appear.
A new window called Figure 1 will appear. Now keep the plot so you can add aNow keep the plot so you can add another linenother line
>>
>> hold on
hold on
The plot z against x The plot z against x>>
>> plot(x,z,'r--')
plot(x,z,'r--')
Now you can label the axes, give your plot a title and
Now you can label the axes, give your plot a title and add a legend. add a legend. Note that you need to use textNote that you need to use text within single quotes for the labels and title.
within single quotes for the labels and title.
>>
>> xlabel('x')
xlabel('x')
>>
>> title('a couple of lines')
title('a couple of lines')
>>
>> legend('y=sin(x)','z=0.5+cos(x/2)')
legend('y=sin(x)','z=0.5+cos(x/2)')
You can specify the axis limits using axis.You can specify the axis limits using axis. For example, to set the x axis from For example, to set the x axis from 0 to 10 and the y axis0 to 10 and the y axis from 5 to 15, type
Plot some data
Plot some data
Make sure the file Lesson2.mat is in your current directory and type Make sure the file Lesson2.mat is in your current directory and type
>>
>> load lesson2
load lesson2
to load some datato load some data to plot. to plot. If the file doesn'If the file doesn't load, typet load, type
ls
ls
to see if you can see the file in your currentto see if you can see the file in your current directory.directory. If you can't If you can't see lesson2.mat when yosee lesson2.mat when you typeu type
ls
ls
, you will have to find the file (it is on my, you will have to find the file (it is on my website if you don't have it, Google Antonia Hamilton) anwebsite if you don't have it, Google Antonia Hamilton) and put it in your current directory. d put it in your current directory. TheThe current directory is shown at the top of the Matlab window.
current directory is shown at the top of the Matlab window. Type
Type
whos
whos
to see what you have got.to see what you have got.data
data
is a matrix of test scores on three different subjects, eachis a matrix of test scores on three different subjects, each repeated ten times.repeated ten times. We need to clear the
We need to clear the old graph to pold graph to plot a new one. lot a new one. You can useYou can use
close all
close all
to close all figureto close all figure windows, orwindows, or
clf
clf
to clear a single figure, orto clear a single figure, orcla
cla
to clear just one axis in a figure.to clear just one axis in a figure.>>
>> close all
close all
First let's just take a look at our data.
First let's just take a look at our data. If you use plot with just oIf you use plot with just one argument, matlab just uses numne argument, matlab just uses numbersbers from 1 to the length of the data on the x axis.
from 1 to the length of the data on the x axis.
>>
>> plot(data,'bo')
plot(data,'bo')
To see if there is a trend, we can plot the mean To see if there is a trend, we can plot the mean
>>
>> hold on
hold on
>>
>> plot(mean(data),'r-^')
plot(mean(data),'r-^')
Or we can use theOr we can use the
errorbar
errorbar
function to plot the mean with error bars.function to plot the mean with error bars.>>
>> errorbar(mean(data),std(data),'g-')
errorbar(mean(data),std(data),'g-')
This is all getting a bit messy, so instead we can plot a new figure with several subplots. You have as This is all getting a bit messy, so instead we can plot a new figure with several subplots. You have as many
many figure windowsfigure windowsopen as you want, and you can putopen as you want, and you can put multiple plotsmultiple plotswithin each window:within each window: Create a new figure called figure 2
Create a new figure called figure 2
>>
>> figure(2)
figure(2)
You can put lots of plots in one figu
You can put lots of plots in one figure with the subplot command. re with the subplot command. You must specify the number of You must specify the number of rows of subplots, the number of
rows of subplots, the number of columns of subplots and the number of columns of subplots and the number of the current subplot in thethe current subplot in the form:
form:
subplot(rows, columns, current)
subplot(rows, columns, current)
Create a set of subplots which will have 2 rows and one column, and make the fi
Create a set of subplots which will have 2 rows and one column, and make the fi rst subplot (countingrst subplot (counting from top left) active.
from top left) active. Then plot data in it Then plot data in it and give it a and give it a title.title.
>>
>> subplot(2,1,1)
subplot(2,1,1)
>>
>> plot(data,'b*')
plot(data,'b*')
>>
>> title('Raw data')
title('Raw data')
>>
>> subplot(2,2,1)
subplot(2,2,1)
>> bar(mean(data),'r')
>> bar(mean(data),'r')
this plots the mean of the data using bars rather than lines this plots the mean of the data using bars rather than lines
>>
>> hold on
hold on
>>
>> errorbar(mean(data),std(data),'k')
errorbar(mean(data),std(data),'k')
>>
>> title('Mean data')
title('Mean data')
Some useful plotting functions are listed in the glossary, or type
Some useful plotting functions are listed in the glossary, or type
help graph2d
help graph2d
to see the completeto see the complete list of graph functions available.list of graph functions available.
You should now know enough to do Exercise E.
Lesson 9 - Basic Scripts
Lesson 9 - Basic Scripts
Typing stuff at the command line quickly gets
Typing stuff at the command line quickly gets confusing if you have a confusing if you have a lot of commands. lot of commands. To avoidTo avoid this, any matlab command you write into the command line can also be w
this, any matlab command you write into the command line can also be w ritten into aritten into a scriptscript, which is, which is basically just a list of commands that are all executed one after another in the order they appear on the basically just a list of commands that are all executed one after another in the order they appear on the screen.
screen.
You can edit scripts in any program you like (notepad, emacs etc) but the matlab script editor has a You can edit scripts in any program you like (notepad, emacs etc) but the matlab script editor has a few advantages.
few advantages. In particular, it highlights the script to shoIn particular, it highlights the script to show you particular words and canw you particular words and can automatically indent loops to look
automatically indent loops to look nice (select File – nice (select File – Preferences-Editor-Indenting-EPreferences-Editor-Indenting-Emacs style smartmacs style smart indenting to get this feature).
indenting to get this feature). Also, if you highlight a chunk of a sAlso, if you highlight a chunk of a script and press F9, matlab runs thatcript and press F9, matlab runs that chunk.
chunk.
To start making a script, type
To start making a script, type
edit
edit
to get the Matlab script editor (if to get the Matlab script editor (if you are in Windows)you are in Windows). . For thisFor this section, write the lines insection, write the lines in
dark green
dark green
ororpurple
purple
in the script editor (they won't appear in purple).in the script editor (they won't appear in purple). Then highlight them and press FThen highlight them and press F9 to run your script. 9 to run your script. If F9 doesn't work, it is beIf F9 doesn't work, it is because you didn't startcause you didn't start the editor by typing
the editor by typing
edit
edit
, (or because you aren't using Windows) but you can cut and paste scripts, (or because you aren't using Windows) but you can cut and paste scripts into the command line instead.into the command line instead. You can save and load scripts usYou can save and load scripts using the menus just like Word, and ing the menus just like Word, and youyou can run a whole script by typing its name in the command line.
can run a whole script by typing its name in the command line. It is good practice to start every script with the line
It is good practice to start every script with the line
clear all
clear all
(unless you specifically want to keep(unless you specifically want to keep previous variables), and aprevious variables), and a commentcommentline saying what the scrline saying what the script does. ipt does. Comment lines begin Comment lines begin withwith , and, and are ignored by Matlab as it runs the script but can be very useful to annotate and explain your code, or are ignored by Matlab as it runs the script but can be very useful to annotate and explain your code, or to cut out lines which aren’t working when you are de
to cut out lines which aren’t working when you are debugging. bugging. Comments can go on a line byComments can go on a line by themselves or at the end of a line of code.
themselves or at the end of a line of code. The
The semicolonsemicolon is a very useful character for sis a very useful character for scripts. cripts. Normally, when you enter a command intoNormally, when you enter a command into Matlab, it responds by showing
Matlab, it responds by showing you the answer to your sum you the answer to your sum or the new value of your variable. or the new value of your variable. ButBut when you are running a script and doing the same sum hundreds of times, you don't need to see the when you are running a script and doing the same sum hundreds of times, you don't need to see the result every time.
result every time. By putting a semi colon at the end of By putting a semi colon at the end of a line, you can suppress the oua line, you can suppress the output so that ittput so that it does not appear on the screen, but Matlab still does the calculation.
does not appear on the screen, but Matlab still does the calculation. Some other useful commands when scripting
Some other useful commands when scripting includeinclude
pause
pause
which pauses the script if you do want towhich pauses the script if you do want to see the output on the screen (hit any key to start the script running again), andsee the output on the screen (hit any key to start the script running again), and Crtl-CCrtl-C(that is, press the(that is, press the Control key and the letter C at the same time) which stops a crashed script and gives you back your Control key and the letter C at the same time) which stops a crashed script and gives you back your command prompt.
command prompt.
Using the example data from the end of
Using the example data from the end of Lesson 6,Lesson 6, we could write a very simple script to find the meanwe could write a very simple script to find the mean of the data in each of 3 categories, put all thes
of the data in each of 3 categories, put all these into a variable mdat and plot the results. e into a variable mdat and plot the results. Enter theEnter the lines below into your script editor
lines below into your script editor
%% this script plots the mean of data for each category
%% this script plots the mean of data for each category
clear all
clear all
data
data
=
=
[4
[4
14
14
6
6
11
11
3
3
14
14
8
8
17
17
17
17
12
12
10
10
18];
18];
cat
cat
= [1
= [1
3 2
3 2
1 2
1 2
2 3
2 3
1 3
1 3
2 3
2 3
1];
1];
mdat(1) = mean(data(cat==1))
mdat(1) = mean(data(cat==1))
mdat(2) = mean(data(cat==2))
mdat(2) = mean(data(cat==2))
mdat(3) = mean(data(cat==3))
mdat(3) = mean(data(cat==3))
figure(1), clf
figure(1), clf
plot(1:3,mdat,'r-*')
plot(1:3,mdat,'r-*')
title('Mean of data for each category')
title('Mean of data for each category')
Once this is written in the script editor, all the lines can be executed by highlighting them and pressing Once this is written in the script editor, all the lines can be executed by highlighting them and pressing F9.
F9. This gives you This gives you a simple and repeatable a simple and repeatable way to do some way to do some analysis. analysis. When you have When you have created a plotcreated a plot like this using Matlab, you have a script so you can always look back and see exactly what you did to like this using Matlab, you have a script so you can always look back and see exactly what you did to get the figure.
get the figure. And if you have a new data set, you can And if you have a new data set, you can often apply the same analysis by just changoften apply the same analysis by just changinging a few characters.
a few characters. This is what makThis is what makes scripting in Mes scripting in Matlab so efficient for atlab so efficient for data processing. data processing. Save thisSave this example as
Lesson 10 - Flow Control
Lesson 10 - Flow Control
A script can run any sequence of commands in the order they appear, but to make scripts really useful, A script can run any sequence of commands in the order they appear, but to make scripts really useful, we need to be able to tell the script to start or stop
we need to be able to tell the script to start or stop at different points. at different points. There are 5 basic commandsThere are 5 basic commands which allow you to do this in Matlab.
which allow you to do this in Matlab.
If
If
If
If
is the most basic control element. is the most basic control element. If an expression is true (or evIf an expression is true (or evaluates to a number other thanaluates to a number other than zero), thezero), the next command next command will execute. will execute. AnAn
if
if
can also have ancan also have anelse
else
, which executes if the first part, which executes if the first part is false or equal to zero, and must have anis false or equal to zero, and must have an
end
end
to finish the command.to finish the command.>>
>> A = 10;
A = 10;
if (A>5)
if (A>5)
B = 1
B = 1
else
else
B = 0
B = 0
end
end
B = 1
B = 1
Try this one out for different values of A Try this one out for different values of A
If
If
statements are often useful for catching errorsstatements are often useful for catching errors. . For example, you could mFor example, you could modify your scriptodify your scriptlesson8.m
lesson8.m
to include these lines (put them straight after you define cat and data).to include these lines (put them straight after you define cat and data).disp('ERROR: Data and categories are not the same length')
disp('ERROR: Data and categories are not the same length')
return
return
%%
%%
return
return
means
means
stop
stop
running
running
the
the
script
script
end
end
The script will now give you a helpful error message if you entered the data wrong. The script will now give you a helpful error message if you entered the data wrong.
For
For
For
For
runs a set of runs a set of commands multiple times commands multiple times in a loop. in a loop. It has aIt has a countercounterwhich tells it how many timeswhich tells it how many times to run through the loop.to run through the loop. The counter can be used within the loop aThe counter can be used within the loop as an index or as a variable buts an index or as a variable but should NOT be changed inside the loop.
should NOT be changed inside the loop.
In the example below, the loop runs once with i=1, so A(1) = 2, then it runs with i=2, so A(2) = 4 etc. In the example below, the loop runs once with i=1, so A(1) = 2, then it runs with i=2, so A(2) = 4 etc. The values of i are specified in the same way as creating a vector with a sequence of values (see The values of i are specified in the same way as creating a vector with a sequence of values (see colons
colons above). above). AA
for
for
loop must always have anloop must always have anend
end
to tell it where to stop, and can also be stoppedto tell it where to stop, and can also be stopped prematurely withprematurely with
break
break
..for i=1:4
for i=1:4
A(i) = i*2
A(i) = i*2
end
end
A = 2
A = 2
A = 2 4
A = 2 4
A = 2 4 6
A = 2 4 6
A = 2 4 6 8
A = 2 4 6 8
As a second example, look at lesson8.m
As a second example, look at lesson8.m again. again. We could replace the three lines which calculate mdatWe could replace the three lines which calculate mdat with a
with a
for
for
loop. loop. We put the counter i in the place of the numWe put the counter i in the place of the number which changed between each lineber which changed between each line and the loop will calculate the mean for each category and pand the loop will calculate the mean for each category and put the results in mdat. ut the results in mdat. Obviously whenObviously when there are only three categories, writing the loop does not save much time, but if there were 100 there are only three categories, writing the loop does not save much time, but if there were 100 categories it would.
categories it would.
for i=1:3
mdat(i) = mean(data(cat==i))
mdat(i) = mean(data(cat==i))
end
end
Switch
Switch
A switch loop is like testing lots of ifs one after th
A switch loop is like testing lots of ifs one after the other. e other. It is useful if you want to match a value toIt is useful if you want to match a value to several alternatives.
several alternatives. Put the value you Put the value you want to match in want to match in brackets after thebrackets after the
switch
switch
statement. Eachstatement. Eachcase
case
is a possibility, and if the value matches, then is a possibility, and if the value matches, then next statement will execute. next statement will execute. It none of the casesIt none of the cases matches, the lines aftermatches, the lines after
otherwise
otherwise
will will execute. execute. AAswitch
switch
must have anmust have anend
end
to tell it to stop.to tell it to stop. ((dispdispmeans display text). means display text). Switch loops can also determine if onSwitch loops can also determine if one text string matches another texte text string matches another text string, and are useful for clstring, and are useful for classifying text strings.assifying text strings.
>>
>> A = 3
A = 3
switch(A)
switch(A)
case 1
case 1
disp(‘A is one’)
disp(‘A is one’)
case 3
case 3
disp(‘A is three’)
disp(‘A is three’)
case 5
case 5
disp(‘A is five’)
disp(‘A is five’)
otherwise
otherwise
disp(‘A is not one or three or five’)
disp(‘A is not one or three or five’)
end
end
‘A is three’
‘A is three’
While
While
While is like a continuous
While is like a continuous
for
for
loop, which keeps going until it gets loop, which keeps going until it gets a false value. a false value. In this example, theIn this example, the loop keeps increasinloop keeps increasing y until y is g y until y is greater than 1. greater than 1. Then x is sThen x is set to 2, so et to 2, so the loop stops. the loop stops. Again, thereAgain, there must be an
must be an