- We started by logging into cpteach and starting matlab.
- We explored assigning numerical values to matrices using commands
like "x=[1,2,3;4,5,6]" etc.
"1,2,3" become the first row and ";" shifts us to the next row "4,5,6".
- We noted matrix creation commands likes "x=ones(3,4)", "y=randn(5,6)".
The former will create a matrix with 3 rows and 4 columns.
We can have column and row vectors with "x=zeros(10,1)" and "y=3*ones(1,10)"
respectively.
One can also have n dimensional variables with "z=ones(3,4,5)".
Note that Matlab functions are often written to be flexible in terms of
input and output arguments so that you "get what you expect".
An example of this is if we give n individual input args we get n-d output but we
can achieve the same effect if we give a single arg which is itself a vector of
numbers.
So "x=ones(3,4,5)" and "x=ones([3,4,5])" give the same result.
One other thing to note is that "z=zeros(10)" gives us a 10x10 matrix -
matlab always "defaults to matrices".
- We investigated matrix indexing syntax.
For instance if we have done "x=[1,2,3;4,5,6]" we can then "x(1,2)" is 2
"x(2,1)" is 4.
We can pull out rows and columns with "x(1,:)" and "x(:,1)",
and a rectangular sub-matrix with "x(1:2,1:2)".
A command to note in this regard is "size(x)" which returns
a row vector containing the size of each dimension of x.
- We tried out the basic matrix visualization function
"imagesc" with "x=randn(10)" followed by "imagesc(x)".
Note can change the colormap using "colormap(jet)" etc
and plot a colorbar with "colorbar".
- We checked out basic statistics functions like "sum(x)"
and "mean(x)" which by default give the sum and mean of each
column of the input matrix.
If the first dimension is "one long" they will instead operate
over the first "non one long" dimension.
Note that such functions normally have an optional additional
argument which tells them which dimension to operate over - like
"sum(x,2)".
In the case of "var(x)" the second arg is taken up with telling
it whether to normalize by n or n-1 so we do "var(x,[],2)" to
tell it to give us the default for the second arg and take the variance
over the second dimension.
- Matlab code consists of functions each stored in a file with the
suffix ".m".
A file can contain sub-functions but these are only visible
internally to that file.
On the other hand the main function in a file is exposed externally
as a function with the same name as the file.
If this file in the current working directory it can be invoked
by typing "x=filename(y)".
There is a path search mechanism whereby the files in many
directories can be simultaneously available just by using their filename.
This encourages code modularity and re-use.
When using Matlab one builds up a set of generally useful "personal toolbox"
files.
It is important to note that this is how largely how Matlab itself is
implemented - the core program does relatively little - most of the
standard functions are themselves ".m" files no different from user
written ones.
For instance typing "which mean" tells us that the function mean
is implemented by file "/usr/local/matlab7p3/toolbox/matlab/datafun/mean.m".
We can open this file with our editor and look at it like any other.
- We opened emacs and wrote our first function "myadd" to add two numbers.
function [c,d]=myadd(a,b)
% c=myadd(a,b)
%
% A function to add two numbers
% actually add the numbers
c=a+b;
d=1;
return
The first line declares this is a function and specifies the names of the input
and output arguments - the name of the function specified here is actually irrelevant,
but the argument lines are very important.
The lines starting with "%" are comments.
The set of lines from the first "%" up until the next line which does not have a "%"
are the help text which appears when one types "help myadd".
(Comment lines after that are just to explain things when actually reading the code.)
In this way ".m" files contain their own documentation.
The rest of the file is hopefully self explainatory - note that we added a dummy
second output argument "d".
We don't have to assign all the output arguments - we can type "x=myadd(3,4)" and the
second output will get discarded.
On more thing - when a matlab statement ends with ";" it surpresses the
output of the result to the keyboard which would normally result.
Except when de-bugging we normally end every line of code with a semicolon.
- We then went on to write our first practical function.
Say we have a set of measured numbers "x=[4,5,6];", and the associated
estimated variance of each of those measurements "v=[0.1,0.2,0.3]".
We want to combine the x's together to get the best estimate of the true
value of x.
The way to do this is to take a weighted mean weighting by the inverse variance of
each measurement.
This is also known as minimum variance weighting because this estimate of the mean can be
shown to have the minimum variance with repect to the true underlying value.
Being scientists we also want to combine the variances so that we can quote
the uncertainty on our combined value of x.
To this end we wrote our first proper function "vwstat":
function [xbar,xvar]=vwstat(x,v,vpow)
% [xbar,xvar]=vwstat(x,v,vpow)
%
% Return the mean and variance of a group of observations of value x
% and variance v combining using the vpow power of the input
% variances
if(isempty(vpow))
vpow=-1;
end
% raise var to desired power
w=v.^vpow;
% normalize the weights to unit sum
w=w./sum(w);
% calc the combined value and var
xbar=sum(w.*x,dim);
xvar=sum((w.^2).*v,dim);
return
Note that we added an extra optional input arg which allows to specify the
power to raise to var to get weights.
Normally this would be -1 but sometimes other values may be preferred - it is
important to remember that we can weight by anything we like and still get an
un-biased answer for x.
- We noticed then this function breaks for more then 1-d input.
To fix that requires use of the "size" and "repmat" functions:
% [xbar,xvar]=vwstat(x,v,vpow,dim)
%
% Return the mean and variance of a group of observations of value x
% and variance v combining using the vpow power of the input
% variances combining along dimension dim
% Default is standard minimum variance combine
if(~exist('vpow'))
vpow=[];
end
if(~exist('dim'))
dim=[];
end
if(isempty(vpow))
vpow=-1;
end
if(isempty(dim))
dim=1; % default to act over col like mean etc
end
% convoluted code so actually works for n-dim input
z=v.^vpow;
n=ones(ndims(z),1);
n(dim)=size(z,dim);
w=z./repmat(sum(z,dim),n);
xbar=sum(w.*x,dim);
xvar=sum((w.^2).*v,dim);
return
- A key feature of matlab is the de-bugger.
To turn it on type "dbstop if error" - when an error then occurs it drops
you out into the function where the error occured with the prompt
changed to "K>>" - even if it's 10 levels
deep into recursion.
One can then use "whos" to see what variables are defined and manipulate and
plot them to try and see what caused the problem.
One can also use "dbup" and "dbdown" to move up and down the hierachy
and "dbstack" to see where you are.
Type "return" when you are done debugging to get back to the base workspace.