Back to tutorial index

Matlab as a graphing scientific calculator (Part II)

Introduction

In this lab, you will learn how to create variables in Matlab and how to create "anonymous functions".

Back to the top

Creating variables in Matlab

So far, we have only entered expressions at the command line, and obtained numerical results. However the real power of any programming language comes from its ability to compute values, store them in named variables, and use these stored values in later computations. On a graphing calculator, you might have used "memory" buttons for this.

Before we start, we are going to clear all global memory to make sure we are starting with a clean workspace. We discuss the clear keyword below.

>> clear all

We will also set the formatting to the "short, scientific notation" style Recall that this style prints four digits after the decimal place, rather than the 16, used in the "long" format.

>> format short e

In Matlab, we store values using an assignment operator = in the following manner :

>> x = 5
x =

5

>> y = 7
y =

7

The values x and y are now stored in Matlab's "global memory", and as long as they are in memory, they can be recalled for later use and can participate in any of the arithmetic operations that we have so far described or used as arguments to functions. For example, we could now make the assignment

>> z = x + y
z =

12

Variable names can be created using the following rules:

Rules for naming variables
1. You may use upper and lower case letters, numbers and the 'underscore' (_) character.
2. Variable names must not begin with numbers or the underscore.
3. Matlab is case sensitive, so the variables A and a are different variables.

Here are some more examples of variable names.

>> x1 = 5
x1 =

5

>> y2 = -25
y2 =

-25

>> pressure = 1000.013
pressure =

1.0000e+03

>> Density = 1.01
Density =

1.0100e+00

>> x_velocity = -56.45
x_velocity =

-5.6450e+01

>> y_veloctiy = 12.0
y_veloctiy =

12

>> Latitude = 180.1
Latitude =

1.8010e+02

>> latitude = -57.8
latitude =

-5.7800e+01

>> alpha_1 = sqrt(pi)
alpha_1 =

1.7725e+00

>> beta_2 = 1/pi
beta_2 =

3.1831e-01

>> big_number = 1e56
big_number =

1.0000e+56

>> small_number = 1e-100
small_number =

1.0000e-100

Back to the top

Word of caution in choosing variable names

Matlab will also allow you to redefine reserved keywords. For example, we can set

>> pi = 3
pi =

3

If we were to now evaluate cos(pi), we would get

-9.8999e-01

instead of the expected value of -1. Worse yet, we can redefine the cos function itself :

>> cos = 4.5
cos =

4.5000e+00

If later in our program, we evaluate the cosine function, we should expect an error.

>> cos(pi)
Index exceeds matrix dimensions.

The precise meaning of this error may not yet be clear (basically, Matlab thinks you are trying to find the third element of the array cos) but it should be obvious why redefining keywords can lead to mysterious errors that can be hard to track down.

Back to the top

Clearing and listing variables from memory

Suppose we want to restore the original meaning of the Matlab keyword cos. We can do this by "clearing" our definition from global memory. Let's also clear our definition of pi as well

>> clear cos pi

When we try our cos function again, we get the expected result.

>> correct_value = cos(pi)
correct_value =

-1

Clearing the variables cos and pi restored the original meaning of these keywords. We can also clear any variables we previously defined. But before we do so, let's see what we have currently stored in memory using the who command

>> who

Density        beta_2         pressure       x_velocity     z
Latitude       big_number     small_number   y
alpha_1        correct_value  x              y2

A similar command whos shows you more detail about each variable in your workspace:

>> whos
Name               Size            Bytes  Class     Attributes

Density            1x1                 8  double
Latitude           1x1                 8  double
alpha_1            1x1                 8  double
beta_2             1x1                 8  double
big_number         1x1                 8  double
correct_value      1x1                 8  double
latitude           1x1                 8  double
pressure           1x1                 8  double
small_number       1x1                 8  double
x                  1x1                 8  double
x1                 1x1                 8  double
x_velocity         1x1                 8  double
y                  1x1                 8  double
y2                 1x1                 8  double
y_veloctiy         1x1                 8  double
z                  1x1                 8  double

This listing shows that each variable we have so far defined is a scalar (a '1x1' array), it occupies 8 bytes, and it is of type double (Matlab uses the term 'class' instead of the more familar 'type').

We can now selectively clear variables from memory and then check what is left in global memory

>> clear pressure Density x y z x1 y2 x_velocity y_velocity
>> whos
Name               Size            Bytes  Class     Attributes

Latitude           1x1                 8  double
alpha_1            1x1                 8  double
beta_2             1x1                 8  double
big_number         1x1                 8  double
correct_value      1x1                 8  double
latitude           1x1                 8  double
small_number       1x1                 8  double
y_veloctiy         1x1                 8  double

If we now try to check the value of one of the variables no longer in memory, we get the following error :

>> Density
Undefined function or variable 'Density'.

To clear all the variables in memory, we use the command

>> clear all

As you might expect, the whos has nothing to show us once we have cleared all variables from memory.

>> whos

Back to the top

Creating 'anonymous' functions in Matlab

In many cases, you will want to evaluate expressions multiple times using different values of the variables. While you might be able to cut and paste the expressions into a script multiple times, this is error prone. It is much better to create a "function" that can be called multiple times using different arguments.

In Matlab, we can create functions in at least two different ways. The first, and simplest, is to create what are called "anonymous functions". These look very much like variables, but take an input argument.

Clear the global memory.

>> clear all;

Define an 'anonymous function' using the special notation

>> f = @(x) 3*x + 2
f =

@(x)3*x+2

The name of this function is called f, and it takes a single argument x. We can now call this function in a very natural way using parenthesis. For example,

>> f(3)
ans =

11

>> f(-1.1)
ans =

-1.3000e+00

>> f(sqrt(7))
ans =

9.9373e+00

>> y = 5
y =

5

>> f(2 - y)
ans =

-7

Here are some general guidelines to observe when creating function handles.

Guidelines for creating function handles.
1. Naming anonymous functions follows the same rules as variable names.
2. Anonymous functions can take multiple arguments
3. Anonymous functions can depend on previously defined variables.
4. Anonymous functions can depend on one another, and can participate in all legal arithmetic expressions.

Here are some examples showing how to apply the above rules.

>> g = @(x) 4*x^2/(2 + x)
g =

@(x)4*x^2/(2+x)

>> pressure = @(temp) 8.314*temp
pressure =

@(temp)8.314*temp

>> temp = 310
temp =

310

>> pressure(temp)
ans =

2.5773e+03

Here is an example of a function which takes multiple arguments.

>> volume = @(h,w,d) h*w*d
volume =

@(h,w,d)h*w*d

>> height = 2.3
height =

2.3000e+00

>> width = 6.1
width =

6.1000e+00

>> depth = 1.2
depth =

1.2000e+00

>> box_volume = volume(height,width,depth)
box_volume =

1.6836e+01

Here is an example of a function which depends on a previously defined variable. In this context, this variable might be called a parameter, since it is not formally an argument to the function. Note that the parameter must be defined before the function itself is defined.

In the following, we create an equation of a line that relies on the slope m and the y-intercept b.

>> m = 3.4
m =

3.4000e+00

>> b = -4
b =

-4

>> my_line = @(x) m*x + b
my_line =

@(x)m*x+b

To call this function, we only pass in the single argument x.

>> my_line(5)
ans =

13

A second way to include parameters in an anonymous function handle is to treat them as additional arguments. For example,

>> my_line = @(x,m,b) m*x + b
my_line =

@(x,m,b)m*x+b

>> my_line(5,3.4,-4)
ans =

13

This in many respects is preferable over the original method, since it is clear exactly what values of m and b the function will use in its definition.

Finally, functions can depend on each other, and can be used in expressions. For example, we can compose two functions to get a third function. Suppose we have funtions $f(x) = x^2$ and $g(x) = x - 7$. We could construct the function $h(x)$ by composing $f$ and $g$ to get $h = f \circ g$, or $h(x) = f(g(x))$.

>> f = @(x) x^2
f =

@(x)x^2

>> g = @(x) x - 7
g =

@(x)x-7

>> h = @(x) f(g(x))
h =

@(x)f(g(x))

And now $h(x)$ can be called like an ordinary function

>> h(10)
ans =

9

Anonymous functions can also be used in expressions in the same way as variables or numerical values.

>> x = -1
x =

-1

>> y = f(x)^2/(sqrt(g(x)) + pi)
y =

1.7581e-01 - 1.5828e-01i

Note that anonymous functions, like variables, appear in global memory when we type whos.

>> whos
Name            Size            Bytes  Class              Attributes

ans             1x1                 8  double
b               1x1                 8  double
box_volume      1x1                 8  double
depth           1x1                 8  double
f               1x1                32  function_handle
g               1x1                32  function_handle
h               1x1                32  function_handle
height          1x1                 8  double
m               1x1                 8  double
my_line         1x1                32  function_handle
pressure        1x1                32  function_handle
temp            1x1                 8  double
volume          1x1                32  function_handle
width           1x1                 8  double
x               1x1                 8  double
y               1x1                16  double             complex

To get more information on function handles, you can consult the Matlab help system. Here is an excerpt from the command line help on the keyword function_handle.

>> help function_handle
............
FUNHANDLE = @(ARGLIST)EXPRESSION constructs an anonymous function and
returns a handle to that function. The body of the function, to the
right of the parentheses, is a single MATLAB expression. ARGLIST is a
comma-separated list of input arguments. Execute the function by
calling it by means of the returned function handle, FUNHANDLE. For
the MATLAB Programming documentation.

To call the function referred to by a function handle value, use ordinary
parenthesis notation.  That is, specify the function handle variable
followed by a comma-separated list of input arguments enclosed in
parentheses. For example, HANDLE(ARG1, ARG2, ...). To call a
function_handle with no arguments, use empty parenthesis, e.g.,
HANDLE().
............

Back to the top

Lab exercises

Use anonymous functions to evaluate the following mathematical expressions.

1. $f(x) = \tanh(x/10)$. Evaluate at $x = 2\pi$ and $x = -e$

2. $h(x) = \frac{3x^3 - 1}{x^2 + 3}$. Evaluate at $x = \sqrt{3}i$ and $x = \sqrt[3]{1/3}$
3. $q(t) = \frac{s(t)}{s(t)^2 + 1}$, where $s(t) = \cos(t)$. Evaluate at $t = \pi$
4. $T(x,y) = 5x^{-2} - 1 + y + \frac{x^2}{2y}$. Evaluate at $x = e^{\pi}, y = \sqrt[4]{5}$
5. Suppose that $f(x) = \cos(x)$ and $g(x) = x^2$. Write function handles for the derivatives of both $f(x)$ and $g(x)$ and use these functions to compute the derivative of a function $h(x) = f(x)g(x)$. What is $h'(-4.561)$?
6. Write a function that computes the distance between two points $(x_1,y_1)$ and $(x_2,y_2)$. Compute the distance between successive minimum and maximums of the function $f(x) = \cos(x)$.
7. Write a function to compute the volume of a sphere of radius $R$. Use your function to compute the volumes of the Earth, Jupiter and Mars.
8. Use the ideal gas law $P=\rho RT$ to compute the density $\rho \; (kg/m^3)$, given the temperature $T \; (K^\circ)$ and pressure $P \; (Pa)$ of a gas. Use the specific gas constant for dry air. $R \approx 287.058 \;(J/(K^\circ\cdot mol)$. What is the density of air at sea level, at 0, 10, 20 and 30 degrees Celsius? Compare your answers with what you can find on the web.

Compare your results with the solutions.

Back to the top