Introduction to using Matlab

Matlab stands for matrix laboratory. It's a very powerful mathematical tool that you can do a lot of things with. Try typing "demo" at the matlab prompt.

The Basics

Calculator functions work as you'd expect:

>(1+4)*3

ans =

15

+ and - are addition, / is division, * is multiplication, ^ is an exponent.

You can assign variables from the matlab workspace. Everything in matlab is a matrix. (If it's a scalar, it's actually a 1x1 matrix, and if it's a vector, it's an Nx1 or 1xN matrix.)

>a = 3

a =

3

To create a vector is pretty similar. Each element is separated by spaces, the whole vectore is in square brackets:

>v = [1 3 6 8 9]

To create a vector of values going in even steps from one value to another value, you would use

>b = 1:.5:10

This goes from 1 to 10 in increments of .5. You can use any increment, positive or negative, you just have to be able to get to the last thing from the first thing, using those increments. If you don't put in an increment, it assumes it's 1, so 1:5 gives you the vector [1 2 3 4 5].

To turn a row vector into a column vector, just put a ' at the end of it. (This is also how to get the transpose of a matrix.) To create a matrix, you could do something like:

c = [1 3 6; 2 7 9; 4 3 1]

The semicolons indicate the end of a row. All rows have to be the same length.

Whenever you assign a value in matlab, it will print out the entire value you have just assigned. If you put a semicolon at the end, it will not print it out, which is much faster.

Dealing with Matrices

Dealing with Matrices

Once you have a matrix, you can refer to specific elements in it. Matlab indexes matrices by row and column. c(3,1) is the element in the third row, 1st column, which is 4. c(2:3,1:2) gives you the elements in rows 2-3, and columns 1-2, so you get

2 7

4 3

as a result. c(1:3,2) gives you the elements in rows 1-3, and the second column, that is, the entire second column. You can shortcut this to:

c(:,2)

literally telling matlab to use all the rows in the second column, ie, the 2nd column.

You can get a whole row of a matrix with

c(1,:)

This literally tells matlab to take the first row, all columns.

You can also refer to any matrix with only one index. It will use that index to count down the columns. c(5) will give you 7, for example.

When you have a matrix or vector (anything with more than one element) you need to do a few things to make sure all of your math does what you want it to. You can add a constant or multiply by a constant normally (const+c, const*c, etc.) If you have data in two matrices that correspond (for example, a time vector and an x position vector that has x values for each point in time), you can add and subtract those normally (it will map each element properly.)

To multiply, divide, or raise to a power when you have a matrix or vector that is acting as a set of data points, you need to use

.*

./

.^

so that matlab will multiply each element in the matrix instead of trying to do matrix multiplication or division.

Of course, it can also treat matrices as actual matrices, so you can solve something like [A]x = b where A is a matrix of coefficients, x is a column vector of the x values you want to find, and b is also a column vector just by doing

x = A\b

after you define A and b. The \ represents "left division" (since to solve that equation you would have to divide both sides by A on the *left* side, since order is significant when dealing with matrices.).

useful functions

Matlab has a lot of built-in functions. To use a function, just type functionname(arguments) with the appropriate name and arguments. If you create a time vector t=1:.25:6; you can get standard functions like

x = sin(t)

which returns a vector the same size as t, with values for the sin of t at all points. You can also do things like

s = sum(c)

which sums all the columns in a matrix c and returns a row vector of the sums. The function d = det(c)

takes a matrix c and returns the determinant of it. The matlab booklet has a list of many of these useful functions.

Help and other tools

Places to get help:

  • Typing "help" at the matlab prompt gives you a list of all the possible directories matlab can find commands in (which also tells you its "search path", or a list of the directories it is looking in for commands.)
  • Typing "help directoryname" gives you a list of the commands in that directory and a short description of them.
  • Typing "help commandname" gives you help on a specific command.
  • Typing "lookfor keyword" gives you a list of commands that use that keyword. ie, "lookfor integral" lists commands that deal with integrals. It's pretty slow, choose the word wisely. You can use control-c to stop searching when you think you've found what you need.
  • Typing "doc" starts up a web browser with the Matlab on Athena home page. This includes the entire reference manual for matlab, a whole lot of other information on using matlab, and a pointer to the Matlab Primer, a good introduction to using Matlab.
  • You can get copies of "Matlab on Athena" at Graphic Arts. You can also get copies of the Matlab Primer mentioned above. (There's a small fee for copying costs on both.)
  • The matlab manual and manuals for many of the toolboxes are available in some clusters and can be borrowed from the consultants' office in 11-115.

Some Useful Tools:

  • If you accidentally reassign a function name to a variable (ie, you try saying sum = 3 and then you get errors when you try to use the sum function because it doesn't know it's a function anymore), you can restore it to its normal state using "clear functionname". You can also use clear to get rid of all variable values with "clear all".
  • who

will tell you all the variables you have currently defined.

  • whos

will tell you the variables, their sizes, and some other info.

  • pi

is a function of that returns the value of pi.

  • eps

is a function that returns Matlab's smallest floating point number. This is useful if you have a vector that might contain zeros that is going to wind up in the denominator of something. If you add eps to the vector, you aren't actually adding anything significant, but you won't run into divide by zero problems anymore.

  • format long

and

format short

switch between the long and short display format of numbers. Either way matlab uses the same number of digits for its calculations, but normally (format short) it will only display the first four digits after the decimal point.

  • Typing

type

functionname for any function in Matlab's search path lets you see how that function is written.

Plotting

The basic syntax to get a plot in matlab is

plot(x1,y1)

(The x values always come before the y values, x1 and y1 represent variables that your data is stored in.) If you type a second plot command later, it will clear your first plot. If you type "hold on" it will hold the current plot so you can add plots on top of one another (until you reset it by typing "hold off".)

You can plot multiple values with plot(x1,y1,x2,y2) and you can specify the color and linetype of a plot as something like plot(x1,y1,'w*') to get white *'s for each data point.

To split your plot into a bunch of smaller plots, you can use the subplot command to split it up into rows and columns.

subplot(r,c,n)

will split the plot window into r rows and c columns of plots and set the current plot to plot number n of those rows and columns. For example, subplot(2,1,1) splits the plot window into two rows in a single column and prepares to plot in the top plot. Then your plot command will plot in the top plot. Then you could switch to the bottom plot with subplot(2,1,2) and use another plot command to plot in the bottom plot.

You can add titles, labels, and legends to plots.

title('This is a Title')

xlabel('My X axis')

ylabel('My Y axis')

legend('First Thing Plotted','Second Thing Plotted')

legend creates a legend box (movable with the mouse) that automatically uses the right symbols and colors and sticks the descriptions in the legend command after them.

Printing, Saving, and Loading

Basic printing

>print -Pprintername

You can also save to a Postscript or Encapsulated Postscript file:

>print -dps filename.ps

>prind -deps filename.eps

You can also save your plot as an m-file (matlab script) which should contain all the commands you need to recreate your plot later. This is about 98 percent accurate.

>print -dmfile filename.m

You can save and load files as either text data or matlab's own data format. If you have a text file consisting of a bunch of columns of data separated by spaces or tabs, you can load it into matlab with

load filename.dat

This command will give you a matrix called filename. Then you can reassign columns of that matrix, ie

col1 = filename(:,1);

When you save data using the command

save filename.mat

, matlab will save all of your variables and their values in its own format, so that when you load it using

load filename.mat

you will have all of your variables already defined and names.

Polynomials and Fitting

Matlab can treat a vector as a polynomial. It will assume that the numbers represent the coefficients of the polynomial going from highest-order to lowest order.

>p = [1 2 2 4 1]

can represent the polynomial x^4 + 2x^3 + 2x^2 + 4x + 1. There are a number of functions that use this representation of polynomials:

>roots(p)

gives you the roots of the polynomail represented by the vector p.

>polyval(p,4)

gives you the value of the polynomial p when x = 4. Similarly,

>polyval(p,[1:10])

gives you the value of the polynomial evaluated at each of the points in the vector. (It returns another vector the same size.)

You can fit polynomials to data sets using this representation and a function called curvefit.

>[p, fitted] = curvefit(x,y,n)

fits the data in x and y to an nth order polynomial (using 1 gives you a straight line, 2 gives you a quadratic, etc), and plots both the data and the fitted curve for you. It returns p, the polynomial representing the equation of the fitted curve, and fitted, the data points you get from the curvefit for each of the x's in your data set.

You can use polyval and the fitted polynomial p to predict the y value of the data you've fitted for some other x values.

>ypred = polyval(p,xvalues)

Logical Conditions and Matrices

Matlab has an interesting way of using logic to choosing elements of matrices. If I have a matrix

a = [ 1 2 3 4 5 6]

and I refer to a(a>3) I will get only the elements of a where a is greater than 3. You can combine these logical statements. Typing "help ops" will list all of the logical functions and operators you can use for this.

I can also create a second matrix the same size as a: b = [7 8 9 10 11 12]

and then referring to b(a<3) will give the elements of b which correspond to where a is less than 3 (that is, [7 8]).

The reason this works is because matlab logical functions are designed to return a matrix or vector of 1's and zeros. If I just typed

> a>3

I would get [0 0 0 1 1 1] as a result. The first 3 elements are zero, because those elements are not greater than 3 (F), and the last are 1 because those elements are greater than 3 (T). Then, matlab can accept matrices like this as a way of specifying indexes for another matrix of the same size. If I just typed

> a([0 0 1 0 0 1]),

I would get [3 6] as a result because those are the elements where 1's appear in the vector I gave as my "index" vector.

This logical indexing capability allows you to do a lot of efficient things with large matrices because you very rarely have to loop through a whole matrix in order to get only specific parts of it. Example: You have a matrix called volt with 50,000 values of voltages over time, and a corresponding matrix called t. To find the mean voltage between time 20 and time 30, you can use

>mean(volt(t>20 & t<30))

to get the result.

Writing Functions and Scripts

All matlab functions and scripts are plain text files that contain matlab commands. Matlab will treat any file that ends in .m as either a function or a script. It can find .m files you've written that are in your ~/matlab directory, in the directory you have cd'd into from the matlab prompt, or in a directory you've started matlab with (ie,

matlab /mit/2.670/Computers/Matlab/Examples

starts up matlab and adds that directory to the places matlab will look for .m files in.)

Scripts

A script is just a list of commands to be run in some order. Placing these commands in a file that ends in .m allows you to "run" the script by typing its name at the command line. You type the name of the script without the .m at the end.

Functions

A function is capable of taking particular variables (called arguments) and doing something specific to "return" some particular type of result. A function needs to start with the line

function return-values = functionname(arguments)

so that matlab will recognize it as a function. Each function needs to have its own file, and the file has to have the same name as the function. If the first line of the function is

function answer = myfun(arg1,arg2)

answer = (arg1+arg2)./arg1

then the file must be named myfun.m. The function has arg1 and arg2 to work with inside the function (plus anything else you want to define inside it, and possibly some global variables as well), and by the end of the function, anything that is supposed to be returned should have a value assigned to it. This particular function is just one line long, and it returns answer, which is defined in terms of the two arguments arg1 and arg2.

Some useful tools for functions and scripts

  • nargin

used within a function tells you how many arguments the function was called with.

You can write functions that can accept different numbers of arguments and decide what to do based on whether it gets two arguments or three arguments, for example.

  • eval

lets you take a string and run it as a matlab command.

For example, if I have to plot 20 similar data files for trials and I want to load each file and use the filename in the title, I can write a function that takes the filename as a string as an argument. To load it in the function, I can use

str = ['load ' filename]

to put together a command string, and

eval(str)

to run that command.

Then to use the filename in the title, I can use

str = ['title(' filename ')']

eval(str)

  • feval

evaluates a function for a given set of arguments. For example, feval('sin',[0:pi/4:2*pi]) is the same thing as saying sin([0:pi/4:2*pi]). If you're dealing with a situation where you might want to specify which function to use as an argument to another function, you might use feval.

Global Variables

When you define a variable at the matlab prompt, it is defined inside of matlab's "workspace." Running a script does not affect this, since a script is just a collection of commands, and they're actually run from the same workspace. If you define a variable in a script, it will stay defined in the workspace.

Functions, on the other hand, do not share the same workspace. A function won't know what a variable is unless the it gets the variable as an argument, or unless the variable is defined as a variable that is shared by the function and the matlab workspace, or a global variable.

To use a global variable, every place (function, script, or at the matlab prompt) that needs to share that variable must have a line near the top identifying it as a global variable, ie:

global phi;

Then when the variable is assigned a value in one of those places, it will have a value in all the places that begin with the global statement.

Loops and Control

Sometimes, you do need to use some kind of loop to do what you need, rather than just operating on an entire matrix or vector at once.

While Loops

The syntax for a while loop is

while (some logical expression)

do something;

do something else;

end

To keep this from going on forever, you should probably be changing some variable in the logical expression within the body of the loop so that it eventually is not true.

For

The syntax for a for loop is:

FOR X = 1:N,

A(X) = 1/(21);

END

You should try to avoid using i and j as counters, since you will wind up redefining i (which is intially defined as the imaginary i.)

If

The syntax for an if statement is

if (logical expression)

matlab command

elseif (other logical expression)