Back to tutorial index

Matlab as a graphing scientific calculator (Part II)

Topics in this lab


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 =


>> y = 7
y =


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 =


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 =


>> y2 = -25
y2 =


>> pressure = 1000.013
pressure =


>> Density = 1.01
Density =


>> x_velocity = -56.45
x_velocity =


>> y_veloctiy = 12.0
y_veloctiy =


>> Latitude = 180.1
Latitude =


>> latitude = -57.8
latitude =


>> alpha_1 = sqrt(pi)
alpha_1 =


>> beta_2 = 1/pi
beta_2 =


>> big_number = 1e56
big_number =


>> small_number = 1e-100
small_number =


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 =


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

>> bad_value = cos(pi)
bad_value =


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

>> cos = 4.5
cos =


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 =


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
Your variables are:

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

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              
  bad_value          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              
  bad_value          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 = 


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 =


>> f(-1.1)
ans =


>> f(sqrt(7))
ans =


>> y = 5
y =


>> f(2 - y)
ans =


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 = 


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


>> temp = 310
temp =


>> pressure(temp)
ans =


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

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


>> height = 2.3
height =


>> width = 6.1
width =


>> depth = 1.2
depth =


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


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 =


>> b = -4
b =


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


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

>> my_line(5)
ans =


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 = 


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


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 = 


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


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


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

>> h(10)
ans =


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

>> x = -1
x =


>> 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
     more information on anonymous functions, see "Types of Functions" in
     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.,

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

Get the code

Do you want to try the above code fragments on your own? Download the Matlab script that produces this page here. (lab_2.m)

Powered by MathJax

Published with MATLAB® 8.5