Transcript Matlabx

Matlab
It’s good
Variables
• Doubles (numbers)
• String (text)
• Cell: a 1x1 size space containing another
variable, of any size, inside it
• Structure (struct): a variable holding other
variables attached to it
Variables: size
• Variables can be considered a martix. They are
always at least 2-dimentional
• A variable with a single number has a size of
1x1
• While a variable such as:
5
6
7.6
8
7
12
55
4.5
• Is 2 x 4 (rows x columns)
Accessing variable elements
• Variable elements can be accessed (or defined)
by the variable name, followed by indices in
brackets.
• Indices are (row, column)
A=
5
6
7.6
8
7
12
55
4.5
• A(1,1) is 5,
A(2,1) is 7,
A(2,3) = 55
• A(2,3) is row 2, third value.
• In a double variable, each number has a separate
index
Defining Variables
• Variables are defined by an = sign
• E.g. A = 5.3 makes a 1x1 double with a value
of 5.3
• Now if we say A(1,2) = 6, we will have a 1x2
variable, [5.3 6]
• Try it!
Defining variables
• Several values can be entered aty once using
square brackets []
• A = [1 2 5 6 7] gives a 1x5. A(1,5) is 7.
• You can also, in simple variables like this, just say A(5)
• A semi colon adds lines
• A = [1 3 5 7; 2 4 6 8]
1
3
5
7
2
4
6
8
• Must have the same number of elements per line
Padding with zeros
• Matlab will expand the size of variables as
needed. In a double, zeros are padded as
needed.
• A=1
• A(6) = 2
• A is now 1 0 0 0 0 2
Colon operator
• In matlab, a colon has two meanings:
– By itself, it means ‘all’
– With numbers on each side it means ‘from x to y’
• E.g. 2:6 = 2 3 4 5 6
• You can use colons inside variable indexs
when calling them
• E.g. A = [2 4 6 8 10 12 14 16]
• B = A(3:5); B is now [6 8 10]
Colon wackiness
• A(1:5) = 10; Ai is now [10 10 10 10 10]
• A = 1:5; A is now [1 2 3 4 5]
• A = 2:2:10; the middle number becomes an
incrimentor
• A is now 2 4 6 8 10
Exercise 1: defining double variables
• Make a double “A” with values 5, 10, 15, 20,
25, 30
• Change the third value to 100
• Make a variable “B” which is equal to the first
3 values in A
• Make a variable “C” which has the same value
as the last value of A (by calling A, not
cheating!)
Pause here to contemplate the nature of existance
Exercise 1b: a matrix, using colons
• Clear
– (this clears all variables from the matlab
workspace)
• A = [1 5 7 9; 11 33 55 77; 100 200 300 400]
• Set Change the 4th value on the first row (the
9) to 3
• Set B equal to the first row of A
• Set C equal to the first 3 numbers in the last
row of A
• Set D as the first COLUMN of A
Error:
In an assignment A(I) = B, the number of elements in B and I must be the
same.
• Matlab tries to fit values into the exact space you
define. If you tell it to fit 4 things in a space of 3
or 5 items, it throws an error:
“In an assignment A(I) = B, the number of elements in B and I must be
the same.”
• For example, A(3:5) = [1 2]
– you are saying “in these 3 spaces, fit 2 things”
• If you give a single value for multiple spaces,
Matlab sets them all to that values
• E.g. A(1:4) = 10, A is [10 10 10 10].
Multiple Dimensions
• Matlab variables are always treated as if they
were AT LEAST 2D, but can in fact have as
much dimensionality as you wish.
• A third dimension can be thought of a cube.
• So:
– A(:,:,1) = [1 2 3; 7 8 9]
– A(:,:,2) = [11 12 13; 21 22 25]
• Now we have a 3D variable of size 2x3x2
• Extra variables can be added (e.g. fMRI data is
typically 4D): a cube, in a ‘room’
Basic Matlab Math
• Matlab treats double variables as matrices, and
will often default to doing matrix math, if you
provide it two matrices
• If you give a matrix an a mathmatical operand
that is a single number, it applies that to all
elements of a matrix
• E.g. A = [1 2 3 4]
• B = A+2; B is now [3 4 5 6]
<<Do some examples together>>
Calling matlab functions
• Matlab has thousands of useful functions you can
call. A function call looks like this:
• Output = functionname(inputs, moreinput, etc)
• Output is any variable name into which the
functions return value is assigned
• Multiple input values are separated by commas
HELP!
• All built-in matlab functions have a help. Type
the word help and the function name
• Try “help sum”
• Lets try calling sum
• A = [1 2 3 4];
• B =sum(A) >> B is now 10 (1+2+3+4)
Sum part 2
• Sum has an option to put in a second input
variable. By default, sum outputs data for
each row of the input
• A = [1 2 3; 4 5 6]
• Sum(a) gives [6 15]
• This is because by default it calls as sum(A,1),
working on the sum based off the first
dimension
• BUT sum(A,2) gives [5 7 9] (1+4, 2+5, 3+6)
Sum of sums, of more sums? Want
sum?
• Since sum only works on one dimension, we can ‘nest it’ go
get a total sum:
• B = sum(sum(A)) NOTE: brackets MUST be balanced!!!!
• B is now 21.
• Matlab evaluates functions inside-out. The ‘deepest’ thing
gets evaluated first.
• <<stop here and marvel at the wonders of nesting>>
• Other basic math functions: mean, min, max, median
Strings
• Matlab treats strngs as an array of charaters
• Strings are defined by encasing in single
quotes
• A = ‘happy’
• Now has a 1x6 variable
h
• A(2) is ‘a’
a
p
p
y
String variables: size matters.
a lot.
• One of the biggest issues with string variables
is the issue of size during variable
assignments.
• Matlab pads strings with whitespace
• When making lists, spaces at the end of
names can be an issue (e.g. a list of file names
to call)
<< examples of using string here>>
Strings are NOT numbers
• A = ‘1’ is a string, not a number
• A+1 is 50. Because when you do math on a
string, it uses asci reference to the string.
• There are useful fucntions for this
• num2str
• str2num
• Examples!
Concatenating strings
• When we assigned double variables, we used
square brackets.
• This can be thought of as concatenating a series
of numbers
• We can also concatinate strings (or other
variables) using []
• E.g. direc = ‘/data/cool/fMRI/’
• file = ‘nicebrain.nii’
• fullfile = [direc file]
Cell:
take a variable, and fit it into a space of 1x1
• Cells are a type of ‘container’ variable to hold
other variables.
• They can be especially useful for strings which
can vary in length.
• Cells are defined by { }
• A{1} = [1 2 3 4] gives a 1x1 sized cell. A(1) is a cell
with a value {1 2 3 4}
• A cell can be ‘extracted’ using curly braces
• B = A{1} gives a 1x4 double variable [1 2 3 4]
Error:
Cell contents assignment to a non-cell array object.
• If you tried the above code you got this
• This is because A is probably defined in your
workspace as a string or double.
• You can only put a cell inside a cell variable
• Do some cell practice here
Saving variables
• Matlab always has a working directory, shown up top
• You can save data with the save command
• “Save mydata” will create a file names mydata.mat in
the current directoy, with all variables from the
workspace
• Load mydata will load this variable IF YOU ARE IN THAT
DIRECTORY
• You can also specify a path
– Load c:/scientceisfun/mydata.mat
• Or as a function call with a string
– Load(‘c:/scientceisfun/mydata.mat’)
• Specific variables can also be saved (see help save)
Scripts and functions
• Matlab has a great editor which allows you to
make scripts and functions
• Scripts just act as if you had copy/pasted the
data into the main matlab windows
• Functions create a new workspace, and only
have access to variables you send to it.
– Functions do not modify variables in your main
workspace, except the output variable!
Script example
• Type edit myscript
• His will open the editor with a file called
myscript.m, which isn’t saved
• Type some commands in there and save
• Now if you type myscript in the matlab
prompt, it will run those commands
Functions
• Functions are defined by having the word
function on the first line, and the function call
e.g. edit myfunc
Function out = myfunc(in)
Out = in* 10;
• Functions do not require an end statement or
anything. They run line by line until the end
• A ‘return’ commend exists the function
Commenting scripts/functions
• Any content starting with a % is treated as a
comment and not run
• A comment can be a while line, or after a
command
• E.g.
A = B %set A to B because SCIENCE
• Comments at the top of a function,
immediately before the function line, will
become the help for that function.
Basic complex syntax
• Most important things in matlab are
completed via only the following steps:
• Define and cotnrol variables (covered, more or
less)
• Calling functions (covered)
• If statements
• For/while loops
If statements
• In Matlab, if statements make code
conditional
• The code following the if will only execute
when the if condition is true
• For a mathmatical equals, use “==“, or
“isequal” (which also works on strings)
• The if code applied until it hits an end
statement
If example
If A == 1
B=A;
A = 2;
end
------------------------------------If A> 1
A = 1;
end
-------------------------------------If A >=2
A=1
end
sSome allowable pp[erands: ==, >, <, <= (less or equal), >=, ~= (not equal)
Else
• An if statements can also have else. In this case,
when the ‘if’ is untrue, an ‘else’ will be run
e.g.
if A == 1
B=A;
A = 2;
else
B =1;
end
elseif
• Elseif runs a new if, ONLY when the first if is
not true
• Can be chained
• Lower elseif only ever run if no above
command is run
• Once any if/elseif is true, onlt that sub-block
of code is run, and then it skips to the end
startment
elseif example
If a < 10
b=1
elseif a > 100
b=3
else %only runs if a is between 11 and 99
b=2
end
*there is no limit on the number of elseifs, though an else has to be the last condition.
**In a chain of elseif’s it is possible none get run. If there is an if and else, at least one is
going to run
For loops
• Probably the most important code in matlab
• Iterates a variable, usually a double
for idx = 1:10 %is use idx by convention, any name is OK
%code goes here
end
If can also call a variable
Or a specified series of numbers,
e.g.
For ii = [1 2 5 6 8 10]
• Like if, the loop terminates with an ‘end’ statement. A
‘break’ can also kill a loop
Loops in loops
• For loops and if statement can be nested
count =1;
for idx = 1:20
a(idx) = sum(b(idx,:));
if a(idx) > 100
for jdx = 1:5
c(idx,jdx) = a(idx) + jdx;
end
elseif a(idx) > 1000
break
end %end of if
d(idx) = a(idx);
count = count+1;
End %end for idx
While loops
• While works are in other programming
formats, only running while/if the condition is
true
• When it hits the end, it returns to the while
and checks the condition
n=1; a=1;
while n < 10
a = a+b(n); %lets assume “b” was defined above somewhere
if a < 10
n = n+1;
end %end if
end %will now check is n is still less than 10
Try and switch
• ‘try’ will try to run the code. If the code fails,
instead of crashing matlab will go the end
• Switch allows testing multiple conditions
switch method
case {'linear','bilinear'}
disp('Method is linear')
case 'cubic'
disp('Method is cubic')
end
Structure variable
• Structures are variables encasing other variables by name.
• Like pointers
• Attached “sub-variable” defined by a “.”
e.g. A.dat = [1 2 3]
Creates a struct variable A, with sub variable “dat” which is a
1x3 double.
• Structures are useful to save lots of data into a single
variable, keeping thing organized
• Can be nested
• E.g.
– a.dat.name = ‘funfun’
– a.dat.num = [1 2 3 4]
Appendix of useful functions
find
disp
length
size