MatLab Training Course Notes
Session 1

Instructor: Bill Miller
Dynamic Neuroimaging Laboratory
415.502.3726
http://dnl.ucsf.edu

Topics for Session 1

  1. About MatLab and its usefulness
  2. Navigation and useful commands
  3. Basic syntax, variables and math
  4. Basic plotting

1. About MatLab and its usefulness

Matlab is both a program and a programming language. You can look at, plot, and analyze your data with command-line commands, without programming; or you can create programs for analysis, including graphical user interfaces (GUIs - windows with buttons and graphs etc.). The language is easier to work with than low level programming languages like C, C++ and Java, so you can work with your data more quickly, without a lot of coding and debugging. Also, it is highly portable: programs you create in MatLab will run the same way on any computer with MatLab installed.

MatLab ("MATrix LABoratory") is optimized for working with matrices and arrays - a very good way to think about your data and your analysis. On the other hand, it is very slow for repeated loops (i.e. "for", "while"), although there is a compiler you can buy to improve this.

The basic application comes with many built-in functions and tools. You can also buy many more "toolboxes" of functions specialized for particular analysis (e.g., wavelets, signal processing, etc.) The most useful toolboxes for our typical purposes in neuroimaging and neuroelectrophysiology are: signal processing, image processing and statistics toolboxes. In my work, I typically do a lot of basic signal processing and plotting in MatLab, and export the results to a textfile which can be loaded into Excel or other program for the complex statistical analyses.

Take a look at the MatLab website - there is lots of help information, and many useful functions contributed by the company and by users. Also, type "demo" (and Return/Enter) after starting MatLab to see examples of all the nifty things that MatLab can do.


2. Basic navigation and useful commands

Starting MatLab: Once MatLab is started by double-clicking on the MatLab icon, the MatLab logo is briefly displayed, and then the main command window opens; the MatLab prompt is ">>". [In Unix, typing "matlab" from a terminal window starts the application inside the terminal window, changing the prompt to ">>"].

When the application starts, one thing it looks for is a startup.m file which you may have created in a directory MatLab recognizes [or in Unix: in a MatLab directory under your home directory, e.g. /home/bill/MatLab]. The startup.m file can contain any MatLab commands you'd like for initializing the application (for example, setting your default working directory - see example below).

Exiting MatLab: Type "exit" or "quit" followed by the Enter/Return key (or use the Exit command on the File menu).

Basic MatLab components: main window, command line, file editor, graphic figures

The main window has a menu bar [not in Unix] - most of its commands we won't talk about in these sessions as they aren't terribly important for basic operation of the application. One menu command is however very useful: Set Path... in the File menu (see below).

All MatLab operations can be run by typing at the command line prompt (after ">>").

All graphs, images, plots, and graphical user interfaces are displayed in graphic figure windows. Figure windows are highly flexible, with many changeable properties, resizing, graph zooming, etc (see Basic Plotting below).

   Example 
     (type the following at the ">>" prompt to 
      display a line plot of 10 random numbers; 
      hit Return/Enter key after each line)   
  
      figure;
      a=rand(10,1);
      plot(a);

      (To close the graphic figure window click 
        on the top right X box, or type "close")

MatLab also comes with a built-in text file editor, for creating your own functions and scripts: type "edit" at the prompt. We will deal with the editor in later sessions.

Setting directories and listing files: MatLab has borrowed some unix-like commands for setting and viewing the current directory and listing files:

    pwd			see which directory you are in 
			   ("print working directory")
    cd [directory]		change current directory
    ls [filter]		list contents of current directory 
			   ("dir" also works)

When referring to a directory, either "/" or "\" can be used. If there is a space in a directory name, enclose the whole directory name in single quotes. For example:

    Examples
     cd c:\users\mydirectory		changes current directory
     ls *.txt			lists all files in current directory
				   filtered with extension "*.txt"
     ls				lists all files in current directory
     ls 'c:/program files'		lists files in a directory containing a space
				   in the name

     Tip: You can make MatLab start up in your preferred 
            working directory by putting a "cd [directory]" 
            command in your startup.m file.  See the MatLab help
            information for creating a startup.m file

Getting help: MatLab has a variety of online help sources:

Typing "help" at the command prompt lists the directories that MatLab knows about (see Setting the Path below) as well as a brief description of each directory. Each description is actually from the first line of a text file in each directory called "contents.m". If no contents.m file is found, Matlab will show the directory name but not a description.

Typing "help" with one of the listed directories will show all lines of the contents.m file for that directory (usually a list of functions and one-line descriptions)

Typing "help" and a function name lists help information for that function (actually the comment lines at the top of the function file).

    Examples
       help                             lists all the directories on the MatLab path
       help general                     describes general Matlab functions
       help cd                          help for the cd command (a "general" command)

Note: by convention, MatLab help information on a command or function shows its name in upper case. However, MatLab actually only recognizes those commands in lower case!

- Typing "helpdesk" launches the MatLab HTML-based help, including help info on each function, a Java-based search tool, and links to the MatLab website, online manuals and online PDF files (if you've installed these). The PDF manuals are identical to the printed manuals that come with the application. I find that the online helpdesk is particularly useful when you are dealing with figures and setting their properties.

The MatLab website, http://www.mathworks.com is a very useful source of information, with a searchable knowledge base, user and Mathworks contributed functions, toolbox descriptions and third-party products (including a list of 400 books pertaining to MatLab use in various fields).

If you are interested in seriously learning MatLab, but have little programming experience or analysis experience, I suggest getting an introductory book on MatLab (some suggestions), because the manuals are really just lists of functions.

Setting the path: pathtool, path, addpath

In order for MatLab to know where function files, data, and other useful things are, it relies on a list of directories called a "path" (just as in DOS or Unix). Generally, it is nice to keep user created files separate from MatLab's application files and functions, especially if you need to do regular computer hard-disk backups; so you'll want to establish your data and function directories, and then add them to the MatLab path.

The path is permanently stored in a function file called pathdef.m, but it is generally best not to change that file directly; instead use some built-in functions that do it for you. The easiest is the graphical "pathtool" [not in Unix] which can be called from the command line or by the "Set path..." command on the file menu. In the graphical dialog box, select "Add to Path" from its Path menu, choose the desired directory, and then "Save" from the File menu (to save it permanently).

Alternatively, you can use the "addpath" function to add a directory to the current path; this is retained for the current MatLab session, but lost when you exit. To add the directory to the path always, you can add an addpath line to your startup.m file. [Unix users may find this the easiest way to permanently add a directory to the path].

    Examples
      path                          displays the current MatLab path
      addpath c:\mydirectory        adds mydirectory to the path for the current session
      pathtool                      launches the graphical path setting function (PC only)

Other useful commands you may want to look at:

      more [on/off]                 "more on" makes information display one screen at a time
                                       (nice to put in startup.m file)

lookfor [keyword] [-all] searches the MatLab path for your keyword on the first line of help information (or all lines of help if you use "-all") Enormously useful if you are looking for an existing function that does something you want.


3. Basic syntax, variables and math

Basic arithmetic and variables: When you start MatLab, you enter into the "base workspace" where variables can be created and manipulated and viewed. You can create variables and do arithmetic and algebra on the command line as easily as you would do on a piece of paper.

    Example
      a=1                this creates a variable "a" and sets its value to 1

In the above example, matlab displays the result:

a =

     1
In order to prevent matlab from displaying this response to your actions, include a semicolon at the end of the line before hitting the return key:

     a=1;
Conversely, you can always display the value(s) of a variable by typing its name (without the semicolon).

Whos: The "whos" command is very useful for seeing the existing variables you've created in the workspace. Typing "whos" at the command line returns a table of variable names, with their size (number of elements), number of bytes of memory used, and and "class" or type. In the example above, "whos" tells us that we created a one-by-one array of type double which takes 8 bytes of memory. MatLab automatically creates variables as type "double" (double precision floating point), even though in this example, the value 1 looks like an integer. There are other types of variables available in MatLab: integer, string, complex, and you can create new types; we'll deal almost exclusively with the double and string types here.

Clear: The "clear" command erases variables from the workspace. Type "help clear" to learn about how to use it.

  More examples

     1+2             (add 1+2 --> MatLab displays the result  "ans = 3"; "ans" is
                      its default variable name if you don't provide one)
     b=a+10;         (algebra: assuming a was created above with value 1, a new value "b"
                      is created with value 1+10 = 11)
     b-a             (MatLab displays the result, "ans = 10")

Vectors and Matrices: MatLab is optimized to work with matrices and vectors, the stuff of linear algebra, so it is important to understand what they are.

Really, a vector variable is just a matrix variable with only one row or one column, so the matrix concept is the most general one. The power of MatLab is that it can do mathematical operations with vectors and matrices as easily as with single-value variables. In the terminology of computer programming, all variables are considered "arrays" (another term for matrix), whether they contain just one or many elements.

   Examples
     a=[1 2 5 12 100]	defines a vector variable "a" with 5 elements
			    using the square brackets
     a+2			adds 2 to each element of a automatically
			   (ans = 2 4 7 14 102)
     a=[a;a]		redefines a as a two-row matrix using 
			   a semicolon to define the new row
			   (ans = 1 2 5 12 100
				1 2 5 12 100 )

Note that now "a" is a matrix, when before it was a vector (and before that, if you followed the earlier example, "a" was just one number). MatLab allows you to easily change or redefine the value and size of a variable without any special array dimensioning or clearing, as you might have to do in a programming language like C. Also, you aren't required to create "loops" to change more than one value or array element at a time (using "for", "while" etc.) as you do in conventional programming languages; MatLab is "vectorized", that is, designed for dealing with whole vectors and matrices as conventional languages deal with single-value variables. Thus, you can potentially manipulate all of your data with a few operations instead of many operations.

   More examples
     b=eye(3)	use the provided function "eye" to create 
		   a 3-by-3 identity matrix
		   (ones in the diagonal and zeros elsewhere)
     b+3		add 3 to every element of b
     b=[];		redefine b as an empty or "null" array 
		     - can be very useful!

Creating ranges with ":" : In the examples earlier, we've seen how a vector or matrix can be defined using []. In MatLab you can create a vector with range of consecutive values all at once using the semicolon:

      a= [1:10]		"a" is a row vector with the 
			    values from 1 to 10
      a= [0:0.1:10]		"a" is a vector with values 0 through 10
			     in steps of 0.1 (i.e., [0 0.1 0.2 ...])
The colon can be used anywhere you want to define a range, for instance, as we will see in "indexing" below.

Indexing: Once a multi-element variable is defined, you often want to pick out one or more of its values. This is done by typing the name of the variable, and then an "index" or range of indices in parentheses.

     Examples
       a=[1:10];            row vector "a" as in the example above 
       a(1)                 MatLab displays the first element in a, which is the value 1
       a(2:4)               extracts the 2nd through 4th values of a using the colon
       b=a(5:end)           new "b" contains the 5th through 10th values of "a" using "end"
In the last example above, we see that MatLab also has a nice "end" keyword that can be used to denote the last element of an **existing** variable.

When indexing matrices, the convention is: variablename([row(s)], [column(s)])

    Example
       a=[1 2 3; 4 5 6;7 8 9]  a 3-by-3 array
       a(2,2)                  the value of a in row 2 and column 2
       a(3,2:3)                values of a in the bottom row, last 2 columns
       a(:,1)                  values in all rows of first column, using the colon
       a(end,:)                values in the last row, all columns using "end"
Here we see that the colon has another meaning: in indexing it can be used by itself to mean "all rows" or "all columns". Again, "end" means the last index in an already defined range.

Transposing: If you recall from linear algebra, it is often important that the orientation of vectors and arrays be "transposed", for instance, when multiplying matrices and vectors. It can be also useful for readability. Transposing is easily accomplished in MatLab using the single quote character, '.

    Examples
      a=[1:10];            by default, MatLab creates a row vector
      b=a'                 b has the same values as a, but it is a column vector
                            (also, use the "whos" command now to compare a and b)

Strings: A string variable can be easily created by enclosing characters in single quotations. MatLab only uses single quotes (apostrophes) not double quotes for strings. Examples a='Bill was here' row vector of characters with 13 elements b='' an empty string c=['abc';'ddf'] a 2-row character matrix

Strings are defined in MatLab as arrays of type "char", as can be verified by typing "whos" after the above examples. Character variables can be manipulated just as numerical variables (transposed, indexed, etc.). Type "help strings" for further information and a list of string-related functions.

Note also that the single quote is used both for defining a string and to do transposing, just as the semicolon is used both for defining a new row in a matrix (last example above) and at the end of a line to silence MatLab's display of a result.


4. Basic Plotting

MatLab includes very powerful features for easy figure creation, plotting and image display. I'll introduce the most basic features briefly here, and more in the later sessions.

Plotting commands: the most important commands for basic 2-dimensional plotting are illustrated in the following example:

       x=0:0.1:10;         x ranges from 0 to 10 in steps of 0.1
       y=sin(x);           y contains the sin of each value of x
       figure              create an empty figure window             
       plot(y)             plots all of the y values (the values on the x-axis are
                             indexes from 1 to 101)
       plot(x,y)           plots y against x (replacing the old plot on the same
                             figure, now showing the units of x on the x-axis)
       close               closes the figure window
 
In truth, since there wasn't yet a figure window, we could have skipped the "figure" command, as "plot" is smart enough to create one before showing the plot. The plot command has many additional possible arguments, as can be seen by typing "help plot". There are also many other plotting commands for 2-dimensional plotting ("help graph2d") and also for 3-D plotting ("help graph3d").

You can close a figure window by clicking on the upper right X box, using the "close" command on the figure's File menu, or by typing "close" at the command prompt

Zooming: The "zoom [on/off]" command is useful for allowing zooming of a plot with the mouse. Type "zoom" or "zoom on" and then drag the mouse pointer across the plot with the left mouse button held down. This draws a "rubberband box" around a region of the plot; releasing the mouse button zooms the display so that only the portion of the plot in the rubberband box is now shown. You can continue zooming this way as much as you want. Double-click the plot with the left or right button to return to the original state. You can type "zoom off" if you want to turn this feature off.

Image display commands: MatLab can display images as easily as plots. The most basic imaging commands are "image", "imagesc", "colormap", as shown in this example:

     load flujet.mat     load one of MatLab's always available demo images
     image(X)            display the loaded image variable (happens to be capital "X")
                           in a figure window
     image(X/3)          display X with its values divided by 3 - less dramatic!
     imagesc(X/3)        display a rescaled version of X/3 - now like the original!
     colormap(gray)      change the colormap of the image to show just gray values
     zoom                (now use the mouse to zoom on parts of the image (see "Zooming"
                            above)

There are many special kinds of graphs in addition to "image" - see "help specgraph". One can also purchase a whole "image processing" toolbox for MatLab. Type "demo" to launch MatLab's demonstration tour to see many examples of graphing and image handling.

In the next session we'll review MatLab syntax, learn more about plotting, and talk about file loading and saving.