Lab Activity 3
Objectives
In this lab, you will:
- Understand the difference between MATLAB functions and scripts.
- Learn to use function parameters and return values.
- Write a function to compute relativistic kinetic energy.
- Write a function to find the maximum distance to
the
origin
- Write code for the step function.
- Write our own version of the Matlab exp function
References
- Lectures 2 and 3 on MATLAB functions.
- MATLAB Help: Using MATLAB
Programming
and
Data Types
M-File Programming.
- Getting Started with MATLAB: Sections 3.1, 3.2, 4.1,
and
4.2.
Instructions
- In this lab, you will work in
groups.
- Read the instructions for each part before filling out the
answer sheet. Submit one answer sheet per group.
Part 1: MATLAB Functions
As you may recall from Lab 1, a MATLAB script file is just a
text
file containing a list of commands for MATLAB to execute. In this lab
you will create a script and then learn how to create MATLAB
functions, which are similar to scripts
in some ways, and different in other important respects.
Section A: Scripts are just lists of commands.
- First, let's go over writing a script. In this script, we're
going to
use
the rand function to simulate the roll of a die, like you did
in lab 2. The rand function returns a random number in the
range
(0,1) (which means between 0 and 1, but not equal to 0 or 1).
We want a number between 1 and 6, so we need to scale it up to the
range (0,6) by multiplying by 6. But we need an integer, so we can use
the floor function to truncate the decimal part of the value.
This will give us an integer between 0 and 5. So finally, we add 1.
Last week, you did this all in one line. But this time, we're
going
to perform each step one at a time. Open the Matlab editor by typing,
>> edit
Create an M-file by typing the following lines:
a = rand;
b = a * 6;
c = floor(b);
c = c + 1
Click the floppy button icon,

and a new window will open, so type the name "dieroll.m"

Then type the following into your
command
window:
» clear
» who
- Answer Part 1, Question 1.
- What variables are listed in your workspace after you run
the clear
command?
Now type:
» dieroll
» who
As a result, you should get a variable c containing a value
between
1 and 6. Answer Part 1, Question 2.
- What variables are listed in your workspace after running
the script?
This shows us that running a script has exactly the same effect as
typing
all of the commands in the script into the command window.
As another example, delete the first line in your script
file,
so it looks
like this:
b = a * 6;
c = floor(b);
c = c + 1
Save your file, and type the following at the Matlab prompt:
» a = 2.5;
» c = 0;
» dieroll
» c
Notice that the script uses the value of a that we just
assigned.
Also notice what happened to the value of c. That's more
evidence
that running a script is just like typing commands into your command
window.
- Answer Part 1, Questions 3 and 4.
- Are variables that are created within a script accessible
to you
in the
workspace? Y / N
- Can workspace variables be overwritten by a script?
Y / N
Section B: Functions are different from scripts.
- Now let's write a function to simulate a die roll.
In the edit window, click on the new file icon,

Create a new
M-file that looks like this:
function c = rolldice()
a = rand;
b = a * 6;
c = floor(b);
c = c + 1;
We've added a line to the beginning of the file (the function
definition
line) which tells MATLAB that 'rolldice' is the name of this
function, and that the
value
of the ouptut variable c will be the return value of
the
function.
The empty parenthesis ( ) , means that this function doesn't have any
parameters, That is, the user doesn't pass any arguments
when they call the rolldice function.
Also notice that we've added a semicolon to the end of the
lines. This
tells MATLAB not to display the result of that command to the screen.
If
we didn't include the semicolons at the end of each line, we'd see the
result of all four lines every time we call the function.
Save your file as 'rolldice.m' and return to the Matlab command
window.
First, clear the variables from your workspace, and verify that they're
gone.
» clear
» who
Then "call" the function.
» rolldice
What is the result?
- Answer Part 1, Question 5.
- What is returned when you call the 'rolldice'
function?
Now type who, and notice that the only variable is
'ans'.
This
is because calling a function is not the same as running a
script.
As we've said before, running a script is the same as running the
commands
in your command window. But calling a function just gives you the
return
value, without creating the other variables in your workspace. It's
kind
of like asking your friend to run the commands in her command window,
and
just copying the answer. (This behavior has to do with the scope
of variables, which is something we won't discuss here.) To see
that it's really like asking your friend to run the
commands, type
the following in the Matlab command window:
» b = 1234
» rolldice
» b
What is the value of b?
- Answer Part 1, Question 6.
- What is the value of b after calling the 'rolldice'
function?
This goes to show that the b in the command window and the b
in the function are actually two different variables. This is one of
the
ways in which functions differ from scripts.
You can also store the return value into a variable, like
this:
» r = rolldice
That looks just like the way you've used other functions, like rand.
Notice that you can't do this with scripts. Try this:
» r = dieroll
What happened?
- Answer Part 1, Question 7.
- What did you get when you executed r = dieroll ?
Section C: Adding helpful information.
We now have a potentially very useful function for simulating die
rolls. We can also add helpful information to our function. Try typing:
» help rolldice
Not really helpful isn't it?
Go back to your "rolldice.m" file, and enter the following
comments(Copy and Paste).
Make
sure that the comments start on the second line, and no spaces come
before
the %.
function c = rolldice()
% function c = rolldice()
% rolldice: simulate the roll of a six sided die.
% returns a random integer between 1 and 6 inclusive.
a = rand;
b = a * 6;
c = floor(b);
c = c + 1;
Save it, and try this again:
» help rolldice
What do you get this time?
- Answer Part 1, Question 8.
- What do you get after running 'help
rolldice'
the second time?
Section D: Passing parameters to functions.
How often do you roll just one die? Unless you're playing Trivial
Pursuit,
you usually roll at least two dice. Rather than having to call our
function
twice, it would be nice to be able to have the function return as many
die rolls as we need. And we can do this pretty easily. - Modify
your "rolldice.m" file to look like this:
function c = rolldice(n)
% function c = rolldice(n)
% rolldice: simulate the roll of n 6-sided dice.
% returns n random integers between 1 and 6 inclusive.
a = rand(1,n);
b = a * 6;
c = floor(b);
c = c + 1;
By adding the parameter n between the parentheses on the
first line,
we're
telling MATLAB that our function will take one value as an argument
from the user. In
this case, it's the number of dice to simulate.
rand(1,n) returns a vector (size 1 by n) of random
numbers.
Fortunately
for us, the last three lines work just as well on vectors as they do on
scalars, so we don't need to make any more changes.
Suppose we want to simulate five die rolls. Now we can just
type:
» rolldice(5)
What do you get?
- Answer Part 1, Question 9.
- What do you get after running 'rolldice(5)'
?
What happens if you forget the argument?
» rolldice
- Answer Part 1, Question 10.
- What happens if you forget the argument to 'rolldice'?
1) Problem Definition
We will write a Matlab function that computes the kinetic energy of a
particle. We will use Einstein's formula for kinetic energy,

At the Matlab prompt lets first create some variables for the mass
of an electron (in kilograms) and the speed of light (in meters/second)
by typing,
>> m = 9.1093897e-31
>> c = 299792458
Open the Matlab editor by typing
>> edit
2) Refine , Generalize and
Decompose the
problem definition (identify sub-problems, I/O, ...)
Name your function energy
.
The function energy has two
input
parameters, m and v (in this order). The
function energy returns a
value
so name this output variable ke
.
3) Develop Algorithm
This function is very simple and should take no more than two
lines of code. The formula for ke above will be used.
4) Write the function
(the code)
To compute a square root in Matlab you can either use the builtin sqrt
function or use the .^ operator. For example,
sqrt(2) equals 2 .^ 0.5
After you complete your function don't forget to save your function.
Make sure that the name of the function matches the name of the file.
Since a function cannot see the value of c you defined in your
workspace, you will have to make the same assignment in the code for
your function.
5) Test and Debug the code
Let's test your code by typing the following at the Matlab prompt,
>> energy(m, 0)
- Answer Part 2, Question 11.
- What value did Matlab return when you typed energy(m,0)?
>> energy( m , [ 0 , .5*c ])
If this doesn't work correctly then check your code for the use of
.^ rather than ^ or (.* rather than *).
- Answer Part 2, Question 12.
- What value did Matlab return when you typed energy(m,
[0
, .5*c])?
>> energy(m, c)
Remember according to Einstein a
particle (except a photon) cannot be accelerated to the speed of light.
Though it is theorized that it is possible that some particles may go
faster than the speed of light ( tachyons )
- Answer Part 2, Question 13.
- What value did Matlab return when you typed
energy(m,c)?
6) Run the Code
Lets use the plot function to see how the kinetic energy varies
with velocity for a single electron.
Complete the command below by filling in the blanks to create a vector
v that has 200 equally spaced values from 0 to .99*c. Then type the
command at the Matlab prompt.
>> v = linspace( ___________ , _______________ , 200);
- Answer Part 2, Question 14.
- Fill in the blanks with the same values you typed above.
At the Matlab prompt plot the kinetic energy of an electron for the
values of v. That is type,
>> plot(v , energy(m,v))
To compare Einstein's relativistic kinetic energy formula with the
classical kinetic energy formula

we fix the current plot on the figure window so that we can add a
second plot by typing at the Matlab prompt,
>> hold on
then
>> plot( v , .5*m*v.^2 , 'r' )
If you obtain a plot similar to the one shown below then
- Answer Part 2, Question 15.
- Write your code for the function energy in the blanks
given.
You may not need all the lines.

Part 3: Writing your own function: finding the maximum distance to
the
origin
We will use the six step
procedure found in lecture 2-16 to write a computer program.
1) Problem Definition
Your function
should
take a pair of vectors x and y that together
represent a
vector of points. For example, the pair of vectors
x = [5 0 2 -7 8]; y = [3 -3
9
4 8];
represent the points (5,3), (0,-3), (2,9), (-7,4), and (8,8).
You want to write a function that finds out how far the farthest
point
to the origin is. The five points above have distances of 5.83,
3,
9.22, 8.06, and 11.31 from the origin, respectively. So the maximum
distance
from the origin is 11.31.
2) Step 2 (Refine, Generalize, Decompose the problem
definition (i.e., identify
sub-problems, I/O, etc.))
If you closed your edit window then open your edit window by
typing
>>edit
at the Matlab prompt or just restore your edit window if its already
open. Name your function 'max_dist'.
From step one we know that 'max_dist' has two input parameters (two
vectors
of the same length) and 'max_dist' returns one value, a scalar.
- Answer Part 3, Question 16.
- Write the function definition line (i.e. the first line)
for the function 'max_dist'. Use the
variables x, y and z. The inputs will be x and y, while z is the return
value. Don't write the entire function.
3) Develop Algorithm
This part involves some math. Given one point (x1
, y1 ) in the x-y plane then the distance from this point to
the origin (0,0) is
.
For two points x = [ x1 x2
] and y = [ y1 y2 ] then we could
write
the distances as
. The same idea extends to any
number of points.
- Answer Part 3, Question 17,18 and 19.
- For two vectors x = [ x1 x2
] and y = [ y1 y2 ], then x+y in
Matlab gives the result [ x1+ y1
, x2
+ y2 ]. Write a Matlab expression
that creates a vector w = [ x12+ y12
x22
+ y22 ]. (Use only x and y in your
expression,
and don't use subscripting.)
Note that the expression above should work
for any number of points, as long as vectors
x and y have the same length. Don't
include this Matlab code
inside your function.
- The built-in 'sqrt' function computes the square-root, for
example if w
= [ 4 16 ] then sqrt(w) would return the vector
[ 2 4]. Write a Matlab expression which creates the vector
u =
using only the variables x and y. Don't include this Matlab code
inside your function.
- The built-in 'max' function computes the maximum value, for
example
if u = [2 4] then max(u) would return the value 4. Write a Matlab
expression
which
calculates z = max(
)
using only the variables x and y. Include this
statement in your function.
4)Write the Function (Code)
After you finish question 19 you can type in
that Matlab expression in your file for 'max_dist'. Your function is
finished.
5) Test and Debug the Code
After saving your function as "max_dist.m", test the function by typing
the following commands into your MATLAB command window.
>>x = [5 0 2 -7 8];
>>y = [3 -3 9 4 8];
>> max_dist(x,y)
Now plot the points, without connecting the dots, by typing the
following
commands:
>> plot(x,y,'o')
or
>> quiver(0*x,0*y,x,y)
or
>> compass(x,y)
to verify that the point (8,8) is indeed the farthest one from the
origin.
- Answer Part 3, Question 20.
Show one of your plots to your lab TA for a signature for
question 20.
Part 4 : Absolute and Relative Error
1) Problem Definition
We will
write our own function to compute ex
using the Taylor series approximation
at various values of x
where N = 100 using
polynomial function polyval.
The correct Taylor series for ex continues
forever, that is, N = infinity.
By using only a
partial series we are introducing what is called truncation error.
2) Step 2 (Refine, Generalize, Decompose the problem
definition (i.e., identify
sub-problems, I/O, etc.))
If you closed your edit window then open your edit window by
typing
>>edit
at the Matlab prompt or just restore your edit window if its already
open. Name your function my_exp
.
From step one we know that my_exp
has one input parameters named x. The variable x many hold any size
array. The function my_exp
has one output variable named y .
3) Develop Algorithm
We first need to create the polynomial with coefficients
p = [ 1/100!
1/99! 1/98!
... 1/3!
1/2! 1 1];
To do this, first
create the vector [ 1
2! 3! ... 98! 99! 100!] using
the vector 1:100 and Matlab function cumprod . Use the "help
cumprod" Matlab
command if you need to find more information on this function. Yes
there is a missing 1 but we will add that later!
- Answer Part 4, Question 21.
21. Write the code to fill in the blank to assign the values [
1
2! 3! ... 98! 99! 100!]
to the variable named temp.
temp =
____________________________________________________________
Next use the values of
the variable temp from the previous
question and the Matlab function fliplr
create a vector with the values
[
100!
99! 98!
... 3!
2! 1]
- Answer Part 4, Question 22.
22. Write a single Matlab expression that creates the vector above. You
must use the variable temp in your answer.
temp2 =
____________________________________________________________
Now add
the missing 1 by typing,
temp2 =
[temp2 , 1];
Finally,
create our polynomial vector p = [
1/100! 1/99!
1/98! ...
1/3! 1/2! 1 1]
by dividing 1 by the variable temp2.
p =
1./ temp2;
- Answer Part 4, Question 23.
23. Write the line of code that evaluates the polynomial p at the value
x and assign this result to the output variable named y.
y
=
____________________________________________________________
4)Write the Function (Code)
Type the above code into your
function named my_exp .
5) Test and Debug the Code
Matlab already has a function for computing ex
named exp . At the Matlab prompt type,
>> format long e
>> exp(1)
ans
=
2.718281828459046e+000
How good is
our approximation by using polynomial p?
>> my_exp(1)
ans
=
???
How do we measure how accurate our results are?
At the Matlab prompt compute the absolute
error by typing
>> abserror = abs(exp(1) -
my_exp(1))
The absolute
error is definded as the absolute value of the difference
between the correct value and the approximate value or
absolute error = | correct value -
approximate value |
Here we have used the Matlab abs function to compute the
absolute value.
Let's try one more test, at the Matlab prompt type,
>> abserror = abs(exp(50) - my_exp(50))
Your answer is no longer small so our
polynomial approximation is not accurrate in an absolute sense, however
if you type
>> exp(50)
>> my_exp(50)
you note that both numbers are huge and in a
relative sense they are close.
The relative
error is defined as the absolute value of the absolute error
divided by the correct value or
relative error
= | absolute error / correct value |
At the Matlab prompt type,
>> relerror = abs( (exp(50)
- my_exp(50))/exp(50) )
- Answer Part 4, Question 24.
- Is the relative error small ( less than 10-6)?
Circle the correct answer:
TRUE
FALSE
Congratulations! You're done with Lab 3.
Submit your answer sheet to your TA before leaving the lab.