Back to tutorial index

# Matlab as a graphing scientific calculator (Part III)

## Introduction

In this lab, you will learn the basics of plotting in Matlab.

Before we begin, let's clear the workspace of any variable we have previously stored

clear all;
format short

Back to the top

## Using 'linspace' for plotting purposes

For plotting purposes, we will use the linspace command. For example, to divide the interval $[0.2,6.5]$ into 200 subintervals, we use the command

N = 200;                   % Number of subintervals
x = linspace(0.2,6.4,N+1);

Back to the top

## Plotting curves

Matlab has an extremely powerful set of tools for plotting functions in one, two and three dimensions. We will explore some very basic one-dimensional plotting commands here.

Suppose we want to graph the function $$f(x) = \cos(2 \pi x)$$
over the interval (domain) [-2,2]. First, we construct an array x (our domain) over which to compute the function values y. Then evaluate y.

x = linspace(-2,2,101); % Domain over which to plot our function

Evalute the function

y = cos(2*pi*x);       % y value corresponding to x values in our domain

Don't forget to use the semi-colon, or you will print all 101 values to the screen. To create a plot of y verses x, use the Matlab plot command :

plot(x,y) The plot brings up a new window, called a figure window. Near the top of the window, you should see a number associated with this window. This is our first plot, so the figure number is '1'.
To get help on the plot command, use the keyword plot.

>> help plot
plot   Linear plot.
plot(X,Y) plots vector Y versus vector X. If X or Y is a matrix,
then the vector is plotted versus the rows or columns of the matrix,
whichever line up.  If X is a scalar and Y is a vector, disconnected
line objects are created and plotted as discrete points vertically at
X.
.......


Back to the top

## Axis limits

To determine axis limits, Matlab uses the minimum and maximum of your x and y values. In our current example, our x values were in the range $x \in [-2,2]$ and our y were in the range $x \in [-1,1]$. We can change this viewing "window", or axes limits using the axis command.

This command takes an array argument defined using the square brackets []. To adjust the limits on our current figure window, to region $[-1, 1]\times [-2, 2]$. we can use

axis([-1 1 -2 2]) You can set the axis limits for each axis separately using the commands xlim and ylim. For example,

xlim([-2 2])
ylim([-1 1]) restores the axis to their original settings.
To retrieve these values from the current figure window, we just use the xlim and ylim without arguments.

xlim
ans =

-2     2


ylim
ans =

-1     1



You may also want to preserve the aspect ratio of the plot, so that visually, 1 unit of distance on the x-axis is the same as 1-unit on the y-axis. The command

daspect([1 1 1]) is one way to do this. The first two arguments indicate the relative ratio of the x and y axis. The third argument is for the z-axis, and can be always set to 1 for 2d plots.

>> 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.
....................

>> help xlim
xlim X limits.
XL = xlim             gets the x limits of the current axes.
xlim([XMIN XMAX])     sets the x limits.
....................

>> help ylim
ylim Y limits.
YL = ylim             gets the y limits of the current axes.
ylim([YMIN YMAX])     sets the y limits.
....................


Back to the top

Very often, we wish to add additional curves to existing plots. This be easily done with the hold command. First, we will clear the current figure window, re-draw our previous plot, "hold" the state of the first plot, and then add a second plot.

clf
plot(x,y)
hold on
plot(2*x,y/2) To plot a curve in red instead of the default blue, add a color attribute to the plot command :

plot(2*x,y/2,'r') Also available are different line types, e.g. dashed lines, dotted lines, and so on. To use these, you can augment the color command with a line style. For example, to get a dashed line, use the '--' line attribute. Using an additional argument in this string, we can specify both the color and the line type :

plot(4*x,y/4,'k--') Back to the top

## Adding symbols to the plot

We can add symbols to the plot as well. Suppose we want to put a symbols at each maximum value and minimum of the function $$g(x) = \cos(4 \pi x)/4 \\ g'(x) = -\pi\sin(4\pi x)$$. This function has a minimum or maximum whenever $g'(x) = 0$, i.e. at $$x_{minmax} = [-1.5, -1, -0.5, 0, 0.5, 1, 1.5]$$ so we will create a simple array to store these values:

xminmax = [-1.5, -1, -0.5, 0, 0.5, 1, 1.5];

We can now plot a symbol at each $(x,y)$

plot(4*xminmax, cos(2*pi*xminmax)/4,'k.','markersize',30) Note that particulary for the '.' symbol, it is useful (if not critical) to set the marker size. Otherwise, the '.' is too small to see on the plot.

You can experiment with different colors, line styles, and symbols by getting help on the plot command. For example, some common colors, styles and symbols are

>> help plot
........................
Various line types, plot symbols and colors may be obtained with
plot(X,Y,S) where S is a character string made from one element
from any or all the following 3 columns:

b     blue          .     point              -     solid
g     green         o     circle             :     dotted
r     red           x     x-mark             -.    dashdot
c     cyan          +     plus               --    dashed
m     magenta       *     star             (none)  no line
y     yellow        s     square
k     black         d     diamond
w     white         v     triangle (down)
^     triangle (up)
<     triangle (left)
>     triangle (right)
p     pentagram
h     hexagram
......................


Back to the top

## Adding a title and axis labels

A plot is not complete without a title, and axes labels. Use the following commands to add these items to your plot.

xlabel('x')
ylabel('y')
title('A simple plot') You can change the font-size (among other things) by passing additional arguments to the xlabel, ylabel and title commands:

xlabel('x','fontsize',18)
ylabel('f(x)','fontsize',18)
set(gca,'fontsize',18)
title('A simple function','fontsize',18,'fontweight','bold') Back to the top

## Printing the figure window

Eventually, you will want to print you plot for use in other documents, such as Word, Latex, or a webpage. You can produce an image file in any number of formats. A format that works well for most purposes is the % PNG (Portable Graphics Format). To print out your figure using this format, use the print command:

print -dpng simple_function.png

A list of available formats can be found by looking at help on print command.

>> help print
print Print figure or model. Save to disk as image or MATLAB file.
......................
print -device -options filename
If you specify a filename, MATLAB directs output to a file instead of
a printer. print adds the appropriate file extension if you do not
specify one.
.....................
Built-in MATLAB Drivers:
.....................
-depsc2    % Encapsulated Level 2 Color PostScript
.....................
-djpeg % JPEG image, quality level of nn (figures only)
E.g., -djpeg90 gives a quality level of 90.
Quality level defaults to 75 if nn is omitted.
.....................
-dtiff     % TIFF with packbits (lossless run-length encoding)
compression (figures only)
.....................
-dpng      % Portable Network Graphic 24-bit truecolor image
(figures only)


Many of the commands discussed above for adding titles and so on to your plots can be done from menu items in the figure window. These are handy if you plan to make a plot only once. But often, you will run a simulation several times, and would like all of your plot attributes to be added automatically. For this reason, we have discussed mainly the command line methods for modifying plots.

Back to the top

## Clearing and closing graphics windows

To clear the graphics window you can use the clf command, which stands for "clear figure". This only removes any plotting elements from the current figure window but does not close the window itself.

>> clf


To close out a figure window can use the close command.

>> close all


You can selectively close figure windows by supplying an argument to the close command:

>> close(1)


Back to the top

## The EZ way to plot

The easiest way to plot a function using Matlab is to use the ezplot command. At its simplest, this command requires a single argument, the function handle.

close all;
f = @(x) exp(cos(x)).*sin(x);
ezplot(f); By default, ezplots plots over the range $[-2\pi, 2\pi]$. To specify a custom range over which to plot the function, pass in two additional arguments, the left and right endpoints of the range in an two element array.

a = -pi/2;
b = 3*pi/2;
ezplot(f,[a b]); Using ezplot, you can still add titles and axes labels to your plots as before. In fact, it is possible to change most aspects of the plot, such as the line type and color, using what is known as "Handle Graphics".

The main drawback to the ezplot command is that it is somewhat limited. For example, there is no clear way to include parameters in the function, either as pre-defined variables, or as arguments. Because of this limitation, and others, ezplot should be reserved for simple plots of functions of one or two variables of the form $f(x)$ or $g(x,y)$.

Back to the top

## Lab exercises

Create function handles for each of the following functions, using the "dot" operater in your function definition where necessary. Then, for each of the following exercises, plot the requested expressions over the interval $[-5,5]$. $$f(x) = \tan^{-1}(x)$$ $$g(x) = \sqrt{x}$$ $$h(x) = x^3 + (5-x)^2 - 7$$
1. On the same graph, plot $y = f(x)$, $y = f(x/10)$ and $y = f(10x)$.
2. Plot $y = g(f(x))$
3. Plot $y = g(x)f(10h(x))$

For this problem, you will use some basic facts you learned from Calculus I. $$h(x) = \frac{e^{\cos(2\pi x)}}{x^2 + 5}$$
Graph this function over the domain [-5,5]. Provide enough resolution (i.e. number of points) in your plot so you see the features of the plot. Now, using what you remember from Calculus I, do the following
1. For a given x value in the domain [-5,5], plot a line tangent to the curve at point x. Try different values of 'x' so you are convinced that you have the correct secant line.
2. Place a symbol at the point where your line is tangent to the curve
3. On the same plot, graph the derivative of the function, and show that the zero-crossings of the derivatives coincide exactly with the maximum and minimums of the original function. You can indicate this graphically by drawing vertical lines connecting the zero crossings of the derivative with the extrema of the original function.
One of your homework problems will be very similar to this problem, so please use the lab session to ask any questions on Matlab at this point. Next session, we will learn how to use scripts to save commands to a file. 