-Techniques and tricks‎ > ‎Matlab‎ > ‎

# This tutorial should get you up to speed on using Matlab.  It was originally written for students taking Brandeis Nbio136b (Computational Neuroscience, a class Steve TA'd for Larry Abbott back in 2003).  It isn't intended to be a thorough introduction to Matlab, but rather an introduction to the stuff you'd need for the course.  It turns out to be a reasonable first step for learning the language for research as well.

In the following examples, I recommend that you actually type in the examples yourself, rather than cutting and pasting.  The goal is to learn the language, which means you should think about what is being written.  Cutting and pasting isn't really good for that.

Matlab, made by The MathWorks, is a programming environment for working with numerical data and, to a lesser extent, symbolic equations.  Matlab uses an interpreted language, which means the code is compiled and run as you type it in.  For this reason, it is an easy environment in which to perform a few manipulations on some data and plot the output without having to include a lot of the basic declarations required by more traditional programming languages.  In addition, Matlab contains a vast array of built-in functions for performing manipulations on data.

#### First steps

Let's just jump in.  In Matlab, type

a = 5

You've just created a variable called a and set it equal to 5.  If you now type

a*5

Now type

b = a*5;

You've just made a new variable b, and set it equal to the product of the variable a and 5.  By adding a semi-colon, you've surpressed the output from being printed.  Surpressing the output will be important later.

In Matlab, all variables are real-valued matricies (of type "long double" for the programmers out there).  This makes it easy to perform manipulations on groups of related numbers at the same time.  You did not realize it, but the variables you created above are 1x1 matricies.  Let's see how this works.  Type

a = [ 1 2 3 4 5]
b = power(a,2)

You've just recreated the variable a to be the array (1-D matrix) [1 2 3 4 5], and set b to be equal to the square of each of its elements.  You can access values of a and b by using parenthesis.  Type

a(3)
b(4)

and you see the values.  You can also use b(end) or a(end) to see the last element.

#### Plotting

Now let's plot the values using the plot function.  Type

figure(1)
plot(a,b)

This brings up a window and plots a on the horizontal axis and b on the vertical axis.  All figures are numbered in Matlab--you can use any integer you want, and if you just call 'figure' it will make up a number for you.  If you want to print the window, you can do that by choosing print from the file menu.  I recommend using "page setup" to make sure the window maps onto the paper you're using in some good way.

Now let's tackle the only slightly more challenging problem of plotting more than one function at a time.   Type

hold on
plot(a,a,'r')

The hold on command tells Matlab to hold what is currently on the plot if new data is plotted; otherwise, the default behavior is to replace what is there (you can go back to this by typing 'hold off').  The second function simply plots a versus itself in red.  The last argument is a string where you can pass some parameters to the plotting function.  To really get into all of the various options is complicated (type 'help plot' if you want to see), but if you follow the pattern of the examples here you might not need to get into all of the details.

Now we have two plots on the same window.  These plots are lines through the points we have given Matlab.  Suppose we want to show the data points.  We can do this by adding two new plots.  Type

plot(a,b,'o')
plot(a,a,'ro')

This adds two new plots.  The first plots b vs. a using o's at each point.  The second plots a vs. a using o's at each point and the color red.

Now let's add some labels and practice changing the axis limits.

title('First two powers of the integers')
xlabel('Integers')
ylabel('First two powers');
legend('second','first');
axis([0 6 0 50])

This is straightforward enough, but in this course you will often be interested in putting more than one plot on a window for clarity and to save paper.  This is where the subplot command comes in.  Close the window you have been working in either by using close(#), where # is the figure number, or by clicking the close box.

figure(1)
subplot(2,1,1)
plot(a,b);
title('Integers squared');
subplot(2,1,2);
plot(a,a)
title('Integers');

subplot allows you to define an MxN matrix of axes, with the third argument describing which axes to draw in presently.  Here, we define a 2x1 matrix of axes, and plot in the 1st one first and the 2nd one second.

### More operations

Now you can perform some simple operations.  Now let's implement a toy excercise that is somewhat similar to the homework.  Suppose you want to write some code that tells you whenever some function, say a sinewave, has the value of 0.5 or greater.
Off the top of my head, I can think of two basic ways to implement this: using a 'for' loop (the slow way), or using a few carefully chosen Matlab expressions.  Both are fine for this course.  First, let's look at a toy 'for' loop, and then we'll implement the procedure above using a 'for' loop.  Type the following:

for A=[1 2 3 4 5],
A,
end;

for A=a,
A,
end;

for A=1:5,
A,
end;

All of these 'for' loops do the same thing.  The variable A steps through the matrix [1 2 3 4 5], and inside the loop we have asked Matlab to display the value of A.  We have defined the matrix [1 2 3 4 5] three different ways:  explicitly, using our variable a as before, and a new way, using the colon operator.  The colon operator allows you to define a vector as running from a beginning value to an ending value, and optionally using a step different from 1.  Try this below:

A=1:5
A=5:-1:1
A=0:0.1:1

Now you should have a good grasp of the colon operator.  Let's solve the problem we introduced at the beginning of the section with a 'for' loop and plot the result.

T=0:0.01:10; % define T to be a vector running between 0 and 10 in steps of 0.01
sw = [];     % define sw to be an empty vector
th=[];       % define an empty vector for determining if we are exceeding threshold or not
for t=T,     % for each value of T
sw(end+1) = sin(2*pi*t);  % set next value of sw to be the sine of 2*pi*t
th(end+1) = sw(end)>0.5; % add either a 1 or a 0 to th
end;
% now let's plot
figure(1);
subplot(2,1,1);
axis([T(1) T(end) -1.5 1.5]);
plot(T,sw);
subplot(2,1,2);
plot(T,th);
axis([T(1) T(end) -0.5 1.5]);  % set the axis so it looks prettier

Here we've introduced two new operations.  One is the idea of creating an empty vector and adding to it.  If you want to see this more closely, type 'A=[], A(end+1)=[A 1], A(end+1)=[A 1],'.  We've also introduced the comment syntax:  any text on a line following a '%' will not be treated as code.  This will help you remind yourself what you have written, and will help the TAs grade your homework.

Now let's do this same function in a way that takes advantage of Matlab's matrix style.  First, let's use the 'clear' command to clear some of our old variables:

clear T sw th

T=0:0.01:10;
sw=sin(2*pi*T);  % this does all values of T at once
th = sw>0.5; % this does all entries of sw at once
% now let's plot
figure(1);
subplot(2,1,1);
axis([T(1) T(end) -1.5 1.5]);
plot(T,sw);
subplot(2,1,2);
plot(T,th);
axis([T(1) T(end) -0.5 1.5]);  % set the axis so it looks prettier

So hopefully now you are begining to understand how Matlab's language can allow you to briefly perform some complicated manipulations.  If you were doing actual homework, you would want to title these plots and label the y and x axes.

#### Using an m file to save your commands

Up until now you've typed all of your commands directly into the command line.  Of course, for doing your homework, you'll probably want to put your code into a file so you can print it out easily and remember what you have done.  Let's make a 'dot-m' file for the last example.

In the Matlab command window, choose 'New...m file' from the file menu.  Now you have an open text window (note that in unix you need to use your own editor).  Re-type the following lines into the file:

clear T sw th

T=0:0.01:10;
sw=sin(2*pi*T);  % this does all values of T at once
th = sw>0.5; % this does all entries of sw at once
% now let's plot
figure(1);
clf;  % clears figure 1
subplot(2,1,1);
axis([T(1) T(end) -1.5 1.5]);
plot(T,sw);
subplot(2,1,2);
plot(T,th);
axis([T(1) T(end) -0.5 1.5]);  % set the axis so it looks prettier

Now choose 'save'.  Save it as 'hw0.m' or something like that.  Now, before running your 'm' file, make sure you are working in the same directory as your file by typing

pwd

If you're not in that directory, use the 'cd' command to get there:

cd C:\mydir   % PC
cd mymac:dir  % Macintosh
cd /home/user/mymatlab  % UNIX

Now you are ready to run your dot-m file.  Type hw0 and the commands should run.  If you ever want to run an m-file without being in that directory, see 'help addpath'.   We snuck in a command in that last bit of code:  type 'help clf' to see what it is.

#### First homework hints

I would look up the functions 'rand', 'find', 'diff', 'hist', 'std', and 'mean' for the first homework.  The first two excercises are definately solvable using the matrix style, but you'll probably have more trouble doing that for the third problem.

Here's another hint on using 'find' and 'diff'.    Type this

A = [ 1 0 0 1 0 1 0 0 1 0 0 0 0 1]
B = find(A==1)
C = diff(B)

Good luck!