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 a function that returns more than one value.
Use the conditional MATLAB if statement.
Lectures 2 and 3 on MATLAB functions.
MATLAB Help: Using MATLAB
Programming and Data Types
M-File Programming.
MATLAB by Gilat: Sections 6.1, 6.2, 6.7
The MATLAB function 'rand' generates uniform random real
numbers on the interval (0,1). The 'rand' function can generate a
vector or matrix filled with random real numbers.
The command
>>
rand(row,column)
creates a row x column array of reals on the
interval (0,1).
Complete the MATLAB command to create a row vector of 10,000 random integers with either the value 0 or 1 (like flipping a coin heads-1, tails-0). You must use the rand function.
x = floor ( .5 + ___________________________________ );
Write a single MATLAB command to compute the arithmetic average of 10,000 random integers generated by the 'rand' function in question #1 above. Use the MATLAB mean function and the vector x to compute the arithmetic average. Write the MATLAB command and not the answer (approx. .5) that your command returns. Use the MATLAB help facility (doc mean) if you have a question about using the mean function. If your mean isn't between .48 and .52 then probably your answer to #1 is probably incorrect.
_________________________________________________
Fill in the three blanks below to complete a MATLAB command
to create a column vector of 500 random real numbers
with a value between -2*pi and 2*pi.
y = ______________
+ _____________ * rand(_________________________________) ;
(You
can test your code by typing min(y) and max(y). These values should
lie close to -2*pi and 2*pi respectively.)
Now you will learn how to represent polynomials in MATLAB. You will also use the roots and polyval functions that were mentioned in your course notes. See lecture 2 slides 32,33.
MATLAB defines polynomials by a vector of the coefficients of the terms in descending order. For instance, f = 2x + 3 would be represented as f = [2, 3], where the first element of the vector (2) is the coefficient of the first degree term (2 x1) and the second element of the vector is the coefficient of the zero-th degree term (3 x0). Polynomials that do not have a term for each degree of x MUST have a 0 in the vector for that element (e.g., f = 3x3 + 2x is missing the coefficient of the second degree term and the zero-th term, so the vector representation would be f = [3, 0, 2, 0]).
MATLAB provides several built-in functions that work with polynomials in this form. For example, to find the roots of a polynomial, you can simply call the roots function. (Remember, the roots of a polynomial are the values of x where the value of the polynomial is 0.)
To find the roots of the polynomial 2x3 + 15x2 +6x - 1, we type the following into the command window,
>> roots([2 15 6 -1])
Write the result.
___________________________________________________________________
Write the single MATLAB command to find all the roots of -x + x100 . (Don't write the roots, just write the MATLAB command that gives the roots.)
>> p =
__________________________________________________
>>
roots(p)
Hint: x100 - x = x100 + 0*x99 + 0*x98+ ... + 0*x3 + 0*x2 - 1*x + 0 . Create a vector, p [ 1 (followed by 98 0's) -1 0]. Use linspace or zeros function to create the 98 0's.
Use the polyval fucntion to compute the value of x3 + 2x2 + 3 at x=3 . Don't write the solution, just write the MATLAB command that gives you the solution.)
___________________________________________________________________
Fill in the blank with the result that MATLAB gives when you type
the following commands.
>>
x = [ 5.9 5.1 -1 0 4.99 -3.99 ];
>>
floor(x)
ans
=
_____________________________________________________
>>
ceil(x)
ans
=
_____________________________________________________
>>
z = [1 3 5 7 9];
>>
cumsum(z) % note how this differs from the sum function
ans
=
_____________________________________________________
>>
w = 1:2:9;
>>
cumprod(w) % note how this differs from the prod function
ans
=
_____________________________________________________
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.
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 ceil
function to round the decimal part of the value up to an integer
value. This will give us an integer between 1 and 6.
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 (copy and
paste) the following lines:
a = rand; % a is a real number on the interval (0,1) b = a * 6; % b is a real number on the interval (0,6) c = ceil(b); % c is an integer between 1 and 6 inclusive
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 2, 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 2, 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 = ceil(b);
Save your file, and type the following at the MATLAB prompt:
» a = 3.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 2, 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
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 = ceil(b);
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 output 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 by typing the function name in the MATLAB prompt.
» rolldice
What is the result?
Answer Part 2, 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 2, 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 2, Question 7.
What did you get when you executed r = dieroll ?
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 = ceil(b);
Save it, and try this again:
» help rolldice
What do you get this time?
Answer Part 2, Question 8.
What do you get after running help rolldice the second time?
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 = ceil(b);
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 2, Question 9.
What do you get after running 'rolldice(5)' ?
What happens if you forget the argument and try running it like this:
» rolldice
Answer Part 2, Question 10.
What happens if you forget the argument to 'rolldice'?
We will use the six step procedure found in lecture 2-16 to write a computer program.
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
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 .
This function is very simple and should take no more than two lines of code. The formula for ke above will be used.
To compute a square root in MATLAB you can either use the
built-in 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.
Let's test your code by typing the following at the MATLAB prompt,
>> energy(m, 0)
Answer Part 3, 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 3, 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 3, Question 13.
What value did MATLAB return when you typed energy(m,c)?
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 3, 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,
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,
then
>> plot( v ,
.5*m*v.^2 , 'r' )
If you obtain a plot similar to the one
shown below then
Answer Part 3, Question 15.
Write your code for the function energy in the blanks given. You may not need all the lines.

We will use the six step procedure found in lecture 2-17 to write a computer program.
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 the distance of the closest point to the line 2x+3y -5 = 0. From calculus we have the formula for the distance from a point (x,y) to a line Ax+By+C=0 is
d = | Ax+By+C| / sqrt(A2 + B2) where | ...| is the absolute value (the abs function in MATLAB)
By individual calculations we find that the distances of the
points (5,3), (0,-3), (2,9), (-7,4), (8,8) to the line 2x+3y-5=0 are
3.8829 3.8829 7.2111 1.9415 9.7073
so the minimum distance from the line 2x+3y-5 = 0 is 1.9415 and that corresponds to the point (-7,4).
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 'min_dist'.
From step one we know that 'min_dist' has five input
parameters (two vectors x and y of the
same length and A, B and C) and 'min_dist' returns one
value, a scalar.
Answer Part 4, Question 16.
Write the function definition line (i.e. the first line) for
the function 'min_dist'. Use the variables x,
y, A, B, C
and z. The inputs will be x, y,
A, B, C while z
is the return value. Don't write the entire function, just the
function
definition.
____________________________________________________________________
This part involves some math.
Answer Part 4, Question 17.
For two vectors x and y write a
single MATLAB expression that returns a vector of the distances
from the points to the line Ax+By+C = 0.
Hint: Pretend x
and y are scalars (so we only have one point in the
plane specified by (x,y)) and write a formula for the distance
between this point and the line Ax+By+C = 0 using the math formula
shown above. Does your formula work correctly when x and y are
vectors of the same length? If not, then change the operators (
e.g. * to .* ).
z =
_____________________________________________________________________________________________________
Note
that the expression above should work for any number of
points, as long as vectors x and y have the same length.
After you finish question 17 you can type in that MATLAB
assignment statement z = ... in your file for
'min_dist' and save your file.
Write this line of
code in the editor and test your function by typing
>>x =
[5 0 2 -7 8];
>>y = [3 -3 9 4 8];
>>
min_dist(x,y,2,3,-5)
We are not done yet since your function is not
returning the minimum distance. Modify your code now. Hint: Use the min
function.
Answer Part 4, Question 18.
Use the same points as in x and y
above but change the line to -2x+3y-5=0. Write your answer below
when you call min_dist to find the minimum distance
to this
line.
_____________________________________________________
After saving your function as 'min_dist.m', test
the function again by typing the following commands into your MATLAB
command window.
>>x = [5 0 2 -7 8];
>>y = [3 -3 9
4 8];
>> min_dist(x,y,2,3,-5)
ans =
1.9415
Now plot the points, without connecting the dots, by typing the following commands:
>> plot(x,y,'o')
use the hold on command so we can add another plot in the same figure window
>> hold on
Now plot the line 2x+3y - 5 = 0.
>> xvalues = linspace(min(x),max(x),20);
>> yvalues = -(2/3)*xvalues +5/3;
>> grid on
>> plot(xvalues,yvalues)
>> axis([ min(xvalues)-1 max(xvalues)+1 min(yvalues)-1 max(yvalues)+1])
to verify that the point (-7,4) is indeed the closest point to the line 2x+3y - 5 = 0.
We will write our own function to find the maximum and minimum value of n variables. Our function find_max_min_and_make_even_odd will take a system generated random number n as input (a number between 1 and 10), generate n system generated numbers, and return the generated numbers, total number of elements generated, and the maximum and minimum values as maxNum and minNum respectively. To make it more interesting, if n has odd number of elements, we will return maxNum and minNum as odd numbers. If either maxNum or minNum is even, we will change it to the next odd number(s) and return those values instead. Similarly, if n has even number of elements, we will return maxNum and minNum as even numbers. If either maxNum or minNum is odd, we will change it to the next even number(s) and return those values instead. find_max_min_and_make_even_odd should work correctly for any integer values of n. For example, to call the function at the MATLAB prompt, we would type,
>> [numbers, num, maxNum, minNum] = find_max_min_and_make_even_odd(n)
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. Write the following line of
your function as shown below.
>> function [numbers, num, maxNum, minNum] = find_max_min_and_make_even_odd(n)
How do we determine the maximum and minimum number? We can use the MATLAB max and min functions which returns the maximum and minimum value respectively. Type help max and help min in the MATLAB command window to find out how these functions work.
Answer Part 5, Question 19.
19. Write the result MATLAB
returns when you type the following:
>> t = [ 3, 7, 1,
9];
>> max(t)
>> min(t)
ans =
____________________________________________________________
How do we determine if a number
is even or odd? We
can use the MATLAB mod function
which returns the modulus after division. Type help
mod in
the MATLAB command window to find out how it works.
Answer Part 5, Question 20.
Write
the result MATLAB returns when you type the following:
>>
m = 6;
>>
mod(m, 2)
>> n = 7;
>>
mod(n,2)
ans =
____________________________________________________________
In
English our algorithm can be written as follows:
generate n number of random
numbers between 1 and 10
find how many elements n has and
what those elements are
find the max and min values of the
generated numbers
if number_of_elements generated is odd then
make max and min odd
if number_of_elements generated is even
then make max and min even
return generated_numbers, total
number_of_elements, max, and min
That's in pseudo-code, but
in MATLAB you would write,
numbers = ceil(10*rand(1,n));
num = length(numbers);
maxNum =
max(numbers);
minNum = min(numbers);
if ((mod(num,2) == 1) && (mod(maxNum,2) == 0))
maxNum
= maxNum+1;
elseif ((mod(num,2) == 0) && (mod(maxNum,2) ==
1))
maxNum = maxNum+1;
end
if ((mod(num,2) == 1) && (mod(minNum,2) == 0))
minNum
= minNum+1;
elseif ((mod(num,2) == 0) && (mod(minNum,2) ==
1))
minNum = minNum+1;
end
end
We are using the MATLAB if statement. Type help
if in the MATLAB command window to find out how it works.
Type the above code into your function named find_max_min_and_make_even_odd and save your work. Remember MATLAB is case sensitive.
Test your code by typing the following in the MATLAB command window. This following example is showing the result when n = 5. For other values of n, the result will be different.
>>
n = ceil(10*rand(1,1)); % Integer between 1 and 10 inclusive
>>
[numbers, num, maxNum, minNum] = find_max_min_and_make_even_odd(n)
[numbers, num, maxNum, minNum] = find_max_min_and_make_even_odd(5)
numbers =
1 3 6 10 10
num =
5
maxNum =
11
minNum =
1
Now test your code by answering the following questions.
Answer Part 5, Question 21.
21. To check whether our function
correctly identifies odd and even numbers, Type >> n = ceil
(10*rand(1, 1)). Then type,
>> [numbers, num, maxNum,
minNum] = find_max_min_and_make_even_odd(n)
What
values do you get for numbers, num, maxNum, minNum =
__________________________ ?
Answer Part 5. Question 22.
22.
Type >> n = ceil (10*rand(1, 1)). Then type,
>>
[numbers, num, maxNum, minNum] =
find_max_min_and_make_even_odd(n)
What
values do you get for numbers, num, maxNum, minNum =
__________________________ ?