Introduction to MATLAB®

copyright © 2000-2005 by Paul Green and Jonathan Rosenberg

Working with the Command Window

How MATLAB appears when it first launches depends to some extent on what kind of computer you are using and what version of MATLAB you are using. Starting with MATLAB 6 ("Release 12" or higher), you should see the MATLAB Desktop, which includes within it several windows, the most important of which is the MATLAB Command Window. (The function of the other windows is explained in your text, A Guide to MATLAB: for beginners and experienced users, by Hunt, Lipsman, and Rosenberg.) With MATLAB 5 ("Release 11") or earlier, you see only the Command Window, which on a UNIX machine is simply the terminal window from which you started MATLAB (usually by typing matlab). In the command window you should see a prompt that looks like >> or ». Position your mouse there and type

1+1

and hit RETURN. MATLAB should type in response:

ans =
 
     2

In this way you can use MATLAB as a calculator. Try typing sin(pi) and hit RETURN. MATLAB should type in response something like:

ans =
 
     1.2246e-016

MATLAB has recognized sin as referring to the sine function, and pi as referring to p. Of course sin(p)=0, but because of round-off error, MATLAB has given the numerical answer 1.224 x 10-16 (in scientific notation). That's because MATLAB does arithmetic with double-precision numbers, which are only accurate to around 15 decimal places. By default, MATLAB only prints five digits, but you can change this by typing format long and hitting RETURN. Thereafter, MATLAB will print out answers to 15 significant digits (unless you go back to the default by typing format short).

Exercise:

Experiment with using the MATLAB Command Window as a calculator. The basic operations and functions are represented by * for "times", / for "divided by", ^ for powers (i.e., 3^3 means "3 cubed"), abs for absolute value, sqrt for square root, exp for the exponential function to the base e, so exp(1)=2.718281828..., log for the logarithm function to the base e, sin, cos, and tan for the basic trig functions, cosh, sinh, tanh for the basic hyperbolic functions, and asin, acos, atan for the inverse trig functions.

Numerical vs. Symbolic Calculation

It is important to remember that MATLAB, by default, does numerical calculations with double-precision numbers. It can also do exact, i.e., symbolic calculations and algebra, using an accessory called the Symbolic Toolbox, but only if you tell it to. For example, notice what happens if you type sin(sym('pi')) and hit RETURN. MATLAB responds with:

ans =
 
0

The meaning of this is as follows. A string of characters, enclosed in single quotes, is what MATLAB calls a string. The command sym takes a string as an argument and tells MATLAB to interpret this string as a symbolic expression. So sym('pi')) refers not to the approximate number 3.14159265... (which MATLAB denotes simply by pi) but to the exact symbolic number pi. So now when we take the sine, we get the exact answer 0. If you look carefully, you'll see that MATLAB indents its answer when the answer is numerical (double-precision) and prints its answer flush with the left margin when the answer is symbolic. That way you can always distinguish numerical from symbolic output.

The usual way to do symbolic calculations in MATLAB (to avoid having to keep writing such awkward expressions as sym('x') over and over) is to declare certain variables to be symbolic. Such a declaration lasts until you clear the assignment or assign a numerical value to that variable instead. Here's an example. Type syms pi and hit RETURN. That's equivalent to saying, "From now on I want pi to represent the true pi, not the approximation." The command syms declares whatever follows to be a symbolic variable or expression. MATLAB responds with

pi =
 
pi

Note the lack of indentation. If you now type sin(pi) and hit RETURN as before, this time you get

ans =
 
0

If you now type clear pi and hit RETURN, then hit the "uparrow" key twice (a shorthand for recalling the next-to-last command) to recover sin(pi) and hit RETURN, you get back

ans =
 
     1.2246e-016

again.

Working in an M-Book

The document you are currently reading may look like an ordinary Microsoft Word® file, but there's one important difference. It was produced from a Word document that's been enabled to transmit commands in an input cell directly to MATLAB and have the output appear immediately in the document in an output cell. (Input cells are traditionally colored green; output cells are colored blue, to distinguish them from ordinary text.) Such a document is called an M-book. There are several ways to launch an M-book (once they have been enabled on your computer): by clicking on the icon of an existing M-book, by typing notebook in the Command Window, or by using the Open menu item in Word and choosing m-book as the document type. For more on M-books, see Chapter 6 of A Guide to MATLAB. In an M-book, if you want to redo a command, you simply edit the cell in which it appears and re-evaluate the cell. In this course, it will be convenient for you to do most of your work in M-books. Nevertheless, it's useful to know how to run MATLAB from the Command Window, since it often runs much faster that way.

To convert a line of text in an M-book into an input cell, you can either hit CONTROL-RETURN while the cursor is on that line (this not only creates a one-line cell but evaluates it immediately), or else highlight the text and type ALT-N-I, or else use the Notebook menu at the top of the Word window and click on Define Input Cell. (You need one of the last two methods if you want to create a multi-line input cell.) Input cells are identified by black surrounding brackets and the fact that they are set in heavy green Courier type. Here is a typical input cell:

syms x
factor(x^2-4)

ans =
 
(x-2)*(x+2)

Try creating such an input cell in your own M-book and evaluating it, by positioning the cursor in the cell and hitting CONTROL-RETURN. Note MATLAB creates a blue output cell in response. In this output cell you see exactly what MATLAB would respond had you entered your command in the Command Window. In this case, we have a two-line input cell. The first line declares x to be a symbolic variable, and the second line factors an expression involving x. Without the declaration of x to be a symbolic variable, the second line would have resulted in an error message:

??? Undefined function or variable 'x'.

Note that error messages are in red, again to distinguish them from ordinary text (and from input and output).

Simple MATLAB Plots

The easiest way to plot a graph in MATLAB is with the command ezplot. It can take as input either a string or a symbolic expression. Thus ezplot('t^3-t', [-2, 2]) and syms t followed by ezplot(t^3-t, [-2, 2]) are both acceptable ways to plot t3 - t over the interval where t runs from -2 to 2. What happens to the output from a graphics command such as this depends on whether you are working from Command Window or in an M-Book, so try it both ways. If you execute the command from the Command Window (or change the Notebook Options… in the Notebook menu to turn off "Embed Figures in M-Book"), the output will pop up in a separate Figure Window. On the other hand, in an M-Book with "Embed Figures in M-Book" turned on (that's the default), the figure will appear just below the command that produced it. Go ahead and try evaluating:

ezplot('t^3-t',[-2,2])

Once you have produced a plot, you can modify it. If the plot has been produced in a figure window, then commands to modify the plot will change the active figure window. If you are working in an M-Book with embedded figures, however, then commands to modify a plot must go in the same input cell as the plotting command. The command hold on sets a toggle switch so that output from the next plotting command is superimposed on the existing one. The command hold off turns this off again. Thus to find the solutions of the equation sin(x) = x/2, you can superimpose the plots of sin(x) and of x/2 as follows:

syms x; ezplot(sin(x),[-2,2]);
hold on; ezplot(x/2,[-2,2]); hold off

Note that you can separate commands on the same line with semicolons (or commas), though a semicolon will also suppress the printed output (not the graphical output) of a command. Another important command for modifying plots is the axis command, which enables you to modify the scales on the axes. For example, axis tight will cut the axes down to the minimum required to enclose the figure, and axis equal makes the scales on the horizontal and vertical axes the same. This is important to know about if you want your circles to look like circles and not like ellipses. Thus compare the following two ways to plot a semicircle:

ezplot(sqrt(1-x^2),[-1,1])

ezplot(sqrt(1-x^2),[-1,1]); axis equal; axis tight

Getting Help in MATLAB

To use MATLAB effectively, it's important to know how to look up the syntax for hundreds of commands that you can't possibly memorize. There are many ways to get online help. If you remember the name of a command, but can't remember its syntax or all its options, all you have to do is type help followed by the name of the command. For example, try:

help axis

 AXIS  Control axis scaling and appearance.
    AXIS([XMIN XMAX YMIN YMAX]) sets scaling for the x- and y-axes
       on the current plot.
    AXIS([XMIN XMAX YMIN YMAX ZMIN ZMAX]) sets the scaling for the
       x-, y- and z-axes on the current 3-D plot.
    AXIS([XMIN XMAX YMIN YMAX ZMIN ZMAX CMIN CMAX]) sets the
       scaling for the x-, y-, z-axes and color scaling limits on
       the current axis (see CAXIS).
    V = AXIS returns a row vector containing the scaling for the
       current plot. If the current view is 2-D, V has four
       components; if it is 3-D, V has six components.
    AXIS AUTO returns the axis scaling to its default, automatic
       mode where, for each dimension, 'nice' limits are chosen based
       on the extents of all line, surface, patch, and image children.
    AXIS MANUAL freezes the scaling at the current limits, so that if
       HOLD is turned on, subsequent plots will use the same limits.
    AXIS TIGHT sets the axis limits to the range of the data.
    AXIS FILL sets the axis limits and PlotBoxAspectRatio so that
       the axis fills the position rectangle. This option only has
       an effect if PlotBoxAspectRatioMode or DataAspectRatioMode are
       manual.
    AXIS IJ puts MATLAB into its "matrix" axes mode. The coordinate
       system origin is at the upper left corner. The i axis is
       vertical and is numbered from top to bottom. The j axis is
       horizontal and is numbered from left to right.
    AXIS XY puts MATLAB into its default "Cartesian" axes mode. The
       coordinate system origin is at the lower left corner. The x
       axis is horizontal and is numbered from left to right. The y
       axis is vertical and is numbered from bottom to top.
    AXIS EQUAL sets the aspect ratio so that equal tick mark
       increments on the x-,y- and z-axis are equal in size. This
       makes SPHERE(25) look like a sphere, instead of an ellipsoid.
    AXIS IMAGE is the same as AXIS EQUAL except that the plot
       box fits tightly around the data.
    AXIS SQUARE makes the current axis box square in size.
    AXIS NORMAL restores the current axis box to full size and
        removes any restrictions on the scaling of the units.
        This undoes the effects of AXIS SQUARE and AXIS EQUAL.
    AXIS VIS3D freezes aspect ratio properties to enable rotation of
        3-D objects and overrides stretch-to-fill.
    AXIS OFF turns off all axis labeling, tick marks and background.
    AXIS ON turns axis labeling, tick marks and background back on.
    AXIS(H,...) changes the axes handles listed in vector H.

    See also AXES.

For the most complete MATLAB help, you will want to use the Help Browser. Usually it will launch automatically when you launch MATLAB, or you can access it by using the Help item on the menu bar. To access help on a specific command in the Help Browser, type (in the Commmand Window) doc followed by the name of the command. For instance, compare the result of doc axis with that of help axis above. Or search for the item with the search button in the Help Browser, or locate it in the alphabetical index. A little experimentation with the Help Navigator will show you how to find commands to carry out any desired task. Also, typing (in the Command Window) lookfor followed by a keyword will get you a list of all the MATLAB commands with that keyword in their basic description.

The MATLAB Workspace

As you work in MATLAB, you will usually end up defining various variables and objects. These are saved in the MATLAB Workspace. There are two ways to inspect the contents of the Workspace: with the Workspace browser, usually found in the upper left-hand corner of the Desktop, or with the whos command. This lists all the currently defined variables and their "types" (double (i.e., double-precision numeric), string, symbolic, etc.). Most of the time you will see a variable called ans; MATLAB uses this for the last output that you did not explicitly store somewhere else, so the contents of ans will usually change many times during a session. Variables can be removed from the Workspace (for instance, to save memory space) with the clear command. Consider the following example.

a='pi'; b=sym('pi'); c=pi; whos

  Name      Size         Bytes  Class
 
 
  a         1x2              4  char array
  ans       1x1            146  sym object
  b         1x1            128  sym object
  c         1x1              8  double array
  x         1x1            126  sym object
 
 
Grand total is 20 elements using 412 bytes

Here a is of type "char" (a string), b is of type "sym" (symbolic), and c is of type "double".  Allowable variable names must be strings of letters, underscores, and numbers starting with a letter, but both upper-case and lower-case letters are allowed, and MATLAB distinguishes between them. Don't be fooled by the fact that the help lines for a command often refer to the command in all caps; MATLAB's built-in commands are almost all to be typed entirely in lower-case letters.

Problems for Practice

1. Plot y = x2 and y = 2x on the same set of axes. Where do they intersect?

2. Turn on format long, set a=1, and then repeat the command a=(a+2/a)/2 about six times. (For the moment it's easiest to do this from the Command Window with the "uparrow" key. Later we will see how to do this with a loop.) What do you observe, and why? Compare with sqrt(2).

3. As in #2, turn on format long, set a=2, and then repeat the command a = 2*sin(a) about 20 times. (Again, this can best be done with a loop, but for now you can use the "uparrow" key.) What do you observe, and why? Compare with the result of the command fzero(@(x) 2*sin(x) - x, 2). Look at the help text for fzero for an explanation of what it does.

4. Plot cosh(x) and sinh(x) on the same set of axes, with x running from -5 to 5. What do you observe? For an explanation, try syms x; y = simple(cosh(x)-sinh(x)).

5. Compare sin(pi/6) and cos(pi/6) with sin(sym('pi/6')) and cos(sym('pi/6')).