Introduction to MATLAB®
Nancy K. Stanton
based on original versions © 2000-2005 by Paul Green and Jonathan Rosenberg, modified with permission
Working with the Command Window
Launch MATLAB. You should see the MATLAB Desktop which includes several windows, the most important of which is the MATLAB Command Window. (The function of the other windows is explained in Chapter 3 of A Guide to MATLAB® for Beginners and Experienced Users, second edition, by Hunt, Lipsman and Rosenberg.)
In the toolbar, change the Current Directory to the directory or folder where you want to save your work.
In the command window you should see a prompt that looks like >>. Position your mouse there and type
and hit Enter. MATLAB should type in response:
In this way you can use MATLAB as a calculator. Type sin(pi) and hit Enter. MATLAB should type in response something like:
MATLAB recognizes sin as the sine function and pi as the number . Of course , but MATLAB gave the numerical answer (in scientific notation). This is because MATLAB does arithmetic with double-precision numbers, which are only accurate to 15 places. The MATLAB default is to print five digits, but you can change this by typing format long and hitting Enter. Thereafter, MATLAB will print out 15 significant digits (unless you go back to the default by typing format short).
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 (e.g., 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 (often denoted ln), 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 Enter. Matlab responds with
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 number . 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 it 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 Enter. That's equivalent to saying, "From now on I want pi to represent the true , not the approximation." The command syms declares whatever follows to be a symbolic variable or expression. Note the lack of indentation. If you now type sin(pi) and hit Enter as before, you get
If you now type clear pi and hit Enter, then hit the "uparrow" key twice (a shorthand for recalling the next-to-last command) to recover sin(pi) and hit Enter, you get
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 over the interval where runs from -2 to 2.
Once you have produced a plot, you can modify it. 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]); 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:
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, GRID, SUBPLOT, XLIM, YLIM, ZLIM. Overloaded methods: vrjoystick/axis Reference page in Help browser doc axis
For the most complete MATLAB help, you will want to use the Help Browser. It may 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 Command Window) doc followed by the name of the command. For instance, compare the result of doc axis with that of help axis above. You can also 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 right-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 Attributes a 1x2 4 char b 1x1 112 sym c 1x1 8 double x 1x1 112 sym
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.
The MATLAB editor allows you to store a number of MATLAB commands in a script M-file. The file should be divided into units called cells, each beginning with a double percent sign. Here is a typical input cell.
syms x factor(x^2-4)
ans = (x - 2)*(x + 2)
Try creating an M-file and such a cell. Go to the File menu, click on New and then M-file. The MATLAB editor will open a new window. Insert a cell. (Type %% or click on the first %% icon on the last line of the tool bar or go to the Cell menu and click on Insert Cell Break) then Enter. You should now have a blank line. Type the MATLAB commands. Now evaluate the cell with Ctrl+Enter or clicking on the lower left icon on the last line of the tool bar. MATLAB will execute the commands in the cell and display the result in the Command Window. If you accidentally type
the variable y has not been declared symbolic and you get an error message (in red):
??? Undefined function or variable 'y'.
The web page you are reading was produced using MATLAB's editor and publish feature. When you publish the file, MATLAB displays all the commands, output, and graphics in a web page - assuming there are no MATLAB errors. All of the output of a cell appears immediately after all of the input of the cell. This means you want to have lots of cells, so you can tell what output goes with what input.
WARNING If there is an error message, the web page will show that, and MATLAB will show the rest of your input but will NOT execute any of the remaining commands.
You can display formatted text that as far as MATLAB is concerned consists only of comments (not for evaluation). When your file is complete and you are sure there are no errors, you can publish it by going the File menu and clicking on Save File and Publish or clicking on the appropriate icon (the one after the printer icon on the second line of the toolbar). After publishing, you can either display the web page in your web browser or print it out (in order, say, to turn in a homework assignment). You may find the printed version looks better if you open the .html file in Firefox or Internet Explorer and print from there instead of printing from MATLAB's browser.
You are now ready to begin the first MATLAB assignment. Open a new M-file. In the File menu, click on Save As and enter the name of your M-file. Go to the Cell menu and click on Insert Text Markup then on Document Title and Introduction. Replace DOCUMENT TITLE by the title you want to give it (e.g., Introduction to MATLAB Practice Problems) and INTRODUCTORY TEXT by what you want there (e.g., your name). You are now ready to begin doing the first MATLAB assignment. When you have completed it, publish it and print the resulting html to turn in.
Problems for Practice
1. Plot and 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. 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. 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')).