Using Matlab

This page is meant to give you the key concepts to matlab so that you know what to look for in the help files.  It is not intended to be a substitute for the help files.   The Matlab help documents are extremely useful, as is this Matlab primer.

Part I: A few examples

create a variable

a=3

You should see it show up in your workspace window.  It is a 1*1 matrix and if you click on it it should have the value 3 in the first element of the matrix.

Create an array

b=[1 2 3]

create an array using a series

b=1:2:5

Multiply

c=a*b

Create a matrix

d=[1 2 3;4 5 6;7 8 9]

index the matrix

d(2,1)

Notice that the first element is indexed by '1'and not '0'.  Index a whole column or row using the colon operator

d(:,1)

d(1,:)

index using logical indices

d(logical([1 1 0]),1)

d(1,([0 1 1]))

Notice that logical([1 1 0]) = [1 2], so d(logical([1 1 0]),1) really indexes the 1st column of the 1st and 2nd row.  index a matrix using array indices

d(3)

d(4)

index using the 'end' operator

d(1,end)

d(end,1)

index using array indices and the end operator

d(end)

index using a function, and logical array indices

d(logical(mod(d,2)==0))

make an assignment using the colon operator

d(1,:) = [11 22 33]

make an assignment to a column using the ' operator (transpose operator)

d(:,1) = [11 44 77]'

use a compare operator

d>10

make an assignment using a compare operator as logical indices

d(logical(d>5))=10

matrix multiply

a*d

c*d

d*c

a*c*d

d*d

multiply element-by-element (use the .* operator)

d.*d

delete an element

b(2)=[]

delete a row

d(:,2)=[]

Create a string

a='hey'

index the string

a(2)

create a string array

a(2,:)='you'

index the string array

a(2,1)

As you can see, strings are really just matrices. This can be a problem because matrices must be rectangular whereas strings are frequently different different size.  For example, the following won't work because the resulting matrix would not be rectangular:

a(3,:)='get me a drink'

Instead, we can use cell arrays.  Cell arrays are identical to arrays except that they use curly brackets.  Also, each element can be of any size and different elements can be of different data types:

a{1}='hey'

a{2}='you'

a{3}='get me a drink'

a{1,4}=d

Index a cell array

a{2,1}

plot your data on the y axis

data=[1 2 3 7 8 9]

plot(data)

now, put your data on the x axis, with the array 1 2 3 4 5 6 on the y axis

plot(data,1:length(data))

The most important thing you need to learn is how to use Matlab help.   It is extremely valuable.  The windows based help index has a searchable and indexable interface.  The command-prompt help is also useful, e.g.

help plot

Part II: functions and scripts

A script in matlab is any file with a .m file extension.  It is similar to a shell script in that all Matlab commands in the script are run when you run the script.  You can run a script by typing its name in the Matlab shell whenever the file is in the Matlab path.

A function in matlab is any file with a .m file extension where the first non-commented line is of the form:

function [result1, result2...] = functionName(param1, param2,...)

The file name must be functionName.m and be in the Matlab path.  params1, param2,etc are parameters of the funciton and result1, result2, etc are the return values.  (Yes, matlab functions can have more than one return value.)  You can call the function above with:

[a b] = functionName(c, d)

The difference between a script and a function is that a function has it's own name space whereas a script uses the name space of it's calling function (perhaps the command line).

Note that all function parameters and return values are passed by value (except for java objects, which are passed by reference).

Part III: the basics of the environment

Matlab is both a programming language and a programming environment.  The language is far less powerful than C or java, but it is much more clean and concise when used for it's intended purpose: linear algebra.  It is also much more efficient than C is some sense because it can take advantage of sparseness or symmetry in your matrices when you don't know how to, eg, when multiplying, etc.

Matlab is an interpreted language, and the main window on the matlab desktop is the interpreter.   It accepts arithmetic ("1+1"), matlab code ("a+b"), and shell commands ("cd nest/tools/matlab").  Use the TAB button for autocompletion.  Use the UP arrow for last command.  Type a few letters and use the UP arrow for last-command-starting-with-these-letters. 

If you find yourself running the same commands over and over again in the interpreter, you can put them into a script and run the script instead.  A script in matlab is any file with extension ".m" that contains matlab commands and is in the matlab path.  You can edit your path with the "addpath" command (type "help addpath" in the interpreter for more info).  You can add comments to your script with the "%" symbol.  The first block of comments in a script called "myscript.m" are printed to the screen when the user types "help myscript" in the interpreter.

All variables you create are held in the workspace, which is basically your environment or your context.  For example, if I type "A=[1 2 3 4]" then a variable A shows up in the workspace. 

Scripts become cumbersome after a while because you will find naming conflicts in your workspace.  To avoid this, you can create functions, which will have their own workspace, or context.  A function is any script called "functionName.m" where the first line is "function [a,b]=functionName(c,d)".  c and d are parameters to the function and a and b are return values. 

Both parameters and return values are pass-by-value, not pass-by-reference.  This is troublesome because you may want your function to have side effects.  You can use global variables to do this.  Any two workspaces that have a variable defined as global share that variable.  I.e., if your main workspace has a variable declared global and you want to effect it in a function, declare it global in the function also and you have, in a sense, imported it to your local workspace.

Global variables are not the only way to have a variable persist between function calls.  A matlab object is basically a directory that ends with a "@" symbol.  There must be a constructor in that directory that defines a matlab struct, which is the data portion of the object.  The function portion of the object is any function in the directory.  Whenever a function is called on a struct created by the constructor, this object's directory is searched first.  In this sense, objects in matlab are a bunch of structs that have functions associated with them.  It is fundamentally the same as a java object, but without the pretty abstractions.

Note that matlab can freely interact with java objects, and can also call C functions.

NOTE: if you EVER find yourself using a for-loop, think about whether or not you can vectorize that loop (do it using matlab matrix operators).  It is ALWAYS faster.  See "how do I vectorize my code" in the Matlab help files