# 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;

and set the formatting

format short

Back to the top

## A note on the use of the 'semicolon'

So far, any time we have entered an expression at the Matlab prompt, the answer has always been returned to us immediately. And so far, this has been exactly the behavior that we want. However, we will see later that we will want to suppress output. To suppress the output of any expression, simply terminate the expression with a semicolon ';'. In the following, you'll see that no output is printed to the command window.

a = 6.1;

We will define the function $h(x) = \sqrt[3]{x}$

h = @(x) nthroot(x,3);
h(a)
ans =

1.8272



Using the semicolon, we can control exactly when we see the output and when we do not need to see it.

Back to the top

## Constructing arrays using 'linspace'

One of the many advantages of a graphing calculator over other calculators is it ability to visualize the graphs of functions. Now we want to investigate the same capablities in Matlab.

Before we continue, we have to learn some very basic ideas about using arrays in Matlab. These will be needed to define a set of values over which to plot our desired function.

To create a simple array in Matlab, we can use the square bracket notation [] as follows.

v = [1 2 3]
v =

1     2     3



This array contains 3 entries. In some cases, it will be convenient to separate the entries using commas. For example,

v = [1,2,3]
v =

1     2     3



For plotting purposes, we will need to be able to construct much longer arrays. To easily construct an array of equally spaced points between two given numbers, we use the linspace command. Here is how linspace command is described by help:

>> help linspace
linspace Linearly spaced vector.
linspace(X1, X2) generates a row vector of 100 linearly
equally spaced points between X1 and X2.

linspace(X1, X2, N) generates N points between X1 and X2.
For N = 1, linspace returns X2.
...................


For example, we can try:

x = linspace(0,1,11)
x =

Columns 1 through 7

0    0.1000    0.2000    0.3000    0.4000    0.5000    0.6000

Columns 8 through 11

0.7000    0.8000    0.9000    1.0000



Like our simple array x1, the vector x2 is a row vector. But the linspace has automatically filled the array with with 11 equally spaced entries between (and including) the values '0' and '1'.

For larger arrays, we may wish to suppress the output to the screen. We do this by terminating our Matlab commands with a semi-colon (;). Try this

x = linspace(0,1,1001);

The first few entries in x3 are

[x(1)  x(2)  x(3)  x(4)]
ans =

0    0.0010    0.0020    0.0030



We will talk more about indexing arrays in a later lab. For now, we can look at each of these three variables in memory to see that they are the expected lengths.

whos
  Name      Size              Bytes  Class              Attributes

a         1x1                   8  double
ans       1x4                  32  double
h         1x1                  32  function_handle
v         1x3                  24  double
x         1x1001             8008  double



The variable ans is also included in the above list. This is the default variable name used anytime you do not explicitly provide a variable name. In our case, we did not explicitly provide a variable name for the list of the first four entries of x3.

Back to the top

## Arithmetic operations involving arrays

We can include arrays in arithmetic operations almost as easily as we can compute using scalar variables. Again, we will set up a vector containing equally spaced points

x = linspace(0,1,11)
x =

Columns 1 through 7

0    0.1000    0.2000    0.3000    0.4000    0.5000    0.6000

Columns 8 through 11

0.7000    0.8000    0.9000    1.0000



and now

y = 2*x
y =

Columns 1 through 7

0    0.2000    0.4000    0.6000    0.8000    1.0000    1.2000

Columns 8 through 11

1.4000    1.6000    1.8000    2.0000



This simple command produced a variable y whose entries are twice that of all the corresponding entries in x. Here are a few more examples.

z = cos(pi*x)
z =

Columns 1 through 7

1.0000    0.9511    0.8090    0.5878    0.3090    0.0000   -0.3090

Columns 8 through 11

-0.5878   -0.8090   -0.9511   -1.0000


w = log(exp(3*x + 1))
w =

Columns 1 through 7

1.0000    1.3000    1.6000    1.9000    2.2000    2.5000    2.8000

Columns 8 through 11

3.1000    3.4000    3.7000    4.0000


u = x + y - 4*z
u =

Columns 1 through 7

-4.0000   -3.5042   -2.6361   -1.4511   -0.0361    1.5000    3.0361

Columns 8 through 11

4.4511    5.6361    6.5042    7.0000



Back to the top

## Element-wise operations using "dot" operators

You may have noticed that in the above examples, we did not include any expressions involving the multiplication or division of arrays with each other. The reason for this is that whereas addition and substraction and elementary function evaluation are all well defined mathematical meanings when applied to arrays, the operations like x*x are ambiguous. Do we mean a scalar product? Or a matrix multiply in the linear algebra sense? Or something else?

For plotting purposes, the correct answer is "something else". Suppose we wanted to construct a vector y who entries contained the square of each entry of x. If we try

>> y = x*x


we get the error

Error using  *
Inner matrix dimensions must agree.


In fact, we can also get errors using the / or the ^ operators, as the following example illustrate.

>> 1/x

Error using  /
Matrix dimensions must agree.


>> y = x^2

Error using  ^
Inputs must be a scalar and a square matrix.
To compute elementwise POWER, use POWER (.^) instead.


The problem is that Matlab is expecting that dimensions of our matrices agree in some linear algebra sense. But what we want is to apply our operation to each element of the array. To use Matlab terminology, we want an element-wise operation. We do this in Matlab by putting a "dot" in front of our multiplcation, division or exponentiation operators. The resulting "dot" operators are '.*', ./ or '.^'. For example, either one of the following expressions will give us our desired vector y.

y = x.*x
y =

Columns 1 through 7

0    0.0100    0.0400    0.0900    0.1600    0.2500    0.3600

Columns 8 through 11

0.4900    0.6400    0.8100    1.0000


y = x.^2
y =

Columns 1 through 7

0    0.0100    0.0400    0.0900    0.1600    0.2500    0.3600

Columns 8 through 11

0.4900    0.6400    0.8100    1.0000



We can now take the element-wise inverse of each entry of x:

y = 1./x
y =

Columns 1 through 7

Inf   10.0000    5.0000    3.3333    2.5000    2.0000    1.6667

Columns 8 through 11

1.4286    1.2500    1.1111    1.0000



Using exponentiation with dot operator will also work in this case

y = x.^(-1)
y =

Columns 1 through 7

Inf   10.0000    5.0000    3.3333    2.5000    2.0000    1.6667

Columns 8 through 11

1.4286    1.2500    1.1111    1.0000



You notice that the first entry is the special value Inf, which results when we divide by 0.

Back to the top

## Rules for using dot operators

Here is a simple set of guidelines for how to use dot operators to carry out element-wise operations

Guidelines for using the dot operators .*, ./ and .^ for element-wise array operations
1. Multiplication: If both expressions on either side of the mutiplication symbol are arrays, then use the .* operator. If one of the expressions is a scalar, then no dot is needed.
2. Division: If the numerator is a scalar and the denominator is an array, use the ./ operator. If both the numerator and the denominator are arrays, also use the ./ operator. If the numerator is an array, and the denominator is a scalar, then no dot is needed.
3. Exponentiation: If either the base or the power (or both) is an array, use the .^ operator. If neither is an array, then no dot is needed.
4. Addition and subtraction: Dots are never used and are not allowed.
5. For complicated expressions, apply the above rules recursively,

We can now extend our use of the dot operator to more complicated expressions. In each of the following examples, we wish to evaluate the given expression at an array of values x where x is defined as

x = linspace(0,1,11)
x =

Columns 1 through 7

0    0.1000    0.2000    0.3000    0.4000    0.5000    0.6000

Columns 8 through 11

0.7000    0.8000    0.9000    1.0000



Example 1
$$y = \cos(\pi x)\sin(\pi x)$$ where the variable $x$ is an array.

y = cos(pi*x).*sin(pi*x)
y =

Columns 1 through 7

0    0.2939    0.4755    0.4755    0.2939    0.0000   -0.2939

Columns 8 through 11

-0.4755   -0.4755   -0.2939   -0.0000



Example 2
$$y = \frac{\sin(\pi x)}{\cos(\pi x)+2}$$

y = sin(pi*x)./(cos(pi*x)+2)
y =

Columns 1 through 7

0    0.1047    0.2092    0.3126    0.4119    0.5000    0.5624

Columns 8 through 11

0.5729    0.4935    0.2946    0.0000



Example 3
$$y = 2^{10 x}$$

y = 2.^(10*x)
y =

Columns 1 through 6

1           2           4           8          16          32

Columns 7 through 11

64         128         256         512        1024



Example 4
$$y = \exp(-10(x-1)^2)^{-1}$$

y = exp(-10*(x-1).^2).^(-1)
y =

1.0e+04 *

Columns 1 through 7

2.2026    0.3294    0.0602    0.0134    0.0037    0.0012    0.0005

Columns 8 through 11

0.0002    0.0001    0.0001    0.0001



or

y = 1./exp(-10*(x-1).^2)
y =

1.0e+04 *

Columns 1 through 7

2.2026    0.3294    0.0602    0.0134    0.0037    0.0012    0.0005

Columns 8 through 11

0.0002    0.0001    0.0001    0.0001



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)$$

First, construct an array x (our domain) over which to compute the function values y. Then evaluate y.

x = linspace(-2,2,101);
y = cos(2*pi*x);

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 y, use the Matlab plot command :

plot(x,y)

The plot brings up a new window, called a figure windown. 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'.

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.

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


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 can query the graphics handle gca :

get(gca,'xlim')
ans =

-2     2


get(gca,'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 present purposes.

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 value of our last plot, which was a graph of the function $g(x) = f(4x)/4 = \cos(4 \pi x)/4$. This function has zeros whenever $g'(x) = 0$, or when $$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*')

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

Use the linspace function to define an array x containing 11 entries over the range [-1,1]. Then evaluate each of the following expressions to obtain a new array y whose entries are the result of applying the given expression element-wise to each entry of x. The goal is to use only the minimum number of dots necessary.
1. $y = 4x-12$
2. $y = \tanh(x/10)$
3. $y = -2(x + 3)^2 + 5$
4. $y = \frac{3x^3 - 1}{x^2 + 3}$
5. $y = xe^{-x}$
6. $y = \frac{1}{x^2 + 1}$
7. $y = e^{-10(x-2)^2}$
8. $y = (x + 2)^{\sin(2\pi x)}$
9. $y = 5x^{-2} - 1 + x + \frac{x^2}{2}$
10. $y = \cosh^2(\cos(\pi x)) - \sinh^2(\cos(\pi x))$
11. $y = \frac{\sin(2\pi x)}{x + 2} + 2 \pi \log(x + 2) \cos(2 \pi x)$

First, create function handles for each of the following functions. Be sure to use 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[3]{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.