1. Use MATLAB's
to compute each of these results.This is a tedious calculation to do with a hand-calculator, unless you program it. But with MATLAB, this is calculation is completed in one (or three) easy steps. This calculation can be done in one command. We split it up here to help you see the results of each part of the computation.
The sin and exp functions evaluate all of the values that are contained in the variable that is passed to the function. Many predefined functions in MATLAB can accept either scalar variables, vector variables as shown here, or even a matrix of values.
View the contents of each variable you have defined by double-clicking on the variable's name in the
window. The window shows the contents of each variable you select.>> val1 = vec(2)
>> val2 = sin_vec(1:5)
>> val3 = exp_vec(2:3:20)
>> clear
>> vec = 0 : pi/200 : 2*pi;
>> sin_vec = sin(vec);
>> exp_vec = exp(sin_vec);
When you type a semicolon at the end of the command, MATLAB does not echo the answer to the screen. What would be the value of this, if you can’t see your result?
>> plot( vec, sin_vec, 'ro' )
You can now see a plot of your results. Notice how MATLAB plots pairs of points defined by the vectors vec and sin_vec (you may need to enlarge the
window to see the individual points). It is much more common to have MATLAB plot the points as a smooth line (by drawing lines between the points). Modify your previous plot command so that it plots sin_vec vs. vec as a red line:>> plot( vec, sin_vec, 'r-' )
Enter the following command to plot exp_vec vs. vec as a blue dotted line.
>> plot( vec, exp_vec, 'b:' )
Enter the following command to plot both curves on the same plot figure.
>> plot( vec, sin_vec, 'r-' , vec, exp_vec, 'b:' )
The characters in quotes specify the format for each set of points. Try help plot for more format options.
The
is useful for short calculations like this, but it is more convenient to define a new function if you are doing a complex multi-step calculation.Show your plot with both curves to a lab leader
2. Defining your own MATLAB function.
Defining your own functions shows more of the real power of MATLAB. You will now create your own unique function that computes the exponential of the sine of a value that is passed to your function as a parameter.
On your computer where you are saving your work for CS 310, create a new folder named
. You will save the new function definitions that you define for this team lab here.Create a new MATLAB function file by selecting the menu option
,
in the upper-right corner of the window
to the right of the icon).
Edit or enter the following lines into the window.
function results = exp_of_sin(value)
s_val = sin(value);
e_val = exp(s_val);
results = e_val;
end
Save this m-file with the name exp_of_sin.m. This will be the name MATLAB wants to give it when you click on the
icon (on the tab). Be sure to navigate to the MATLAB folder you created in part a and save the file in that folder.In order to run your new function, it needs to be in a place where MATLAB knows to look. Below the ribbon and above the
is the address bar. The address bar shows MATLAB's current working directory and the panel shows the contents of the current working directory. To try out a function you've written, MATLAB's current working directory must be the folder containing the function file.If MATLAB's current working directory is your
folder (and you can see exp_of_sin.m in the ), then you're set. If not, navigate within MATLAB (e.g., using the address bar), to your folder.In the
, try your new function by entering>> exp_of_sin(pi/3)
Note that when the command is executed, it returns only the final result of 2.3774. Note also that you simply enter the function name with an input value, just as you do when calling built-in functions like sin or exp.
Modify (and save) the function definition by changing the last line to
results = [ s_val , e_val ];
In the
, use the up arrow button to repeat the previous command. Note that both results are returned in a single row vector. The sine value is listed first and then the exponential of the sine. The comma indicates that each value is one element in a row. This type of return value is rarely useful. (Think about why this might be the case.)Modify (and save) the function definition by changing the last line to
results = [ s_val ; e_val ];
In the
The results are now in a matrix with a single column. The sine is listed in the first row and the exponential of the sine is in the second row. The semi-colon indicates that each value is in its own row of the result matrix. This type of return value (a column vector of values) is more useful.
Create a script to test your exp_of_sin function: create a new (empty) script by selecting
on the tab, or by selecting on the tab or the tab.Add this header comment at the beginning of your script (and add the names of your team members):
%% Team Lab 5: Functions and Plotting in MATLAB % Team members: % %% Test exp_of_sin
Put a clear command after the line with %% Test exp_of_sin and save the script as teamLab5.m
First, test exp_of_sin with a scalar value. Add code to your script to assign the value pi/3 to a variable, such as angle, and then use that as the argument of a call to your exp_of_sin function.
angle = pi/3;
soln = exp_of_sin(angle)
Save and run the test script to see that it is working as expected.
Your own function works the same way as built-in functions. You can assign its results to a variable that you can later use for additional calculations.
Next, use your function to compute the sine and exponential of a vector (a list) of values. Add the following to your teamLab5 script and then run the updated script:
angleVec = [ 0 : pi/100 : 2*pi ];
soln = exp_of_sin(angleVec)
Note that the results are returned as a matrix. The first row contains the results for the sine value and the second row contains the results for the exponential value. This is the matrix equivalent to the result that you obtained for a single input value, but now with multiple input values, you are returned multiple output results.
Separate the sine and exponential rows into individual variables using the commands (in your script)
s_values = soln(1, :);
e_values = soln(2, :);
What does the notation (1, :) mean? What would soln(:, 1) return? Make a guess and then run your updated script to see.
Plotting results in MATLAB always requires that you evaluate the function that you want to plot at closely spaced points and then plot the point pairs. We will do this many times as we learn to use MATLAB. Add these commands to plot to your test script. Be sure that you understand what each command line does.
plot(angleVec, s_values, 'g', angleVec, e_values, 'k')
title('sin and exponential of sin for angles 0 to 2\pi')
xlabel('angle (radians)')
ylabel('sin(angle) and exp(sin(angle))')
Modify your plot command so that:
Show your test script and updated plot results to a lab leader.
Define a new function exp_of_sin_2 that returns the sine and exponential of sine as two separate variables instead of two rows in a single variable. The function header changes to:
function [s_val , e_val] = exp_of_sin_2(value)
and the function body will be:
s_val = sin(value);
e_val = exp(s_val);
Save this m-file with the name exp_of_sin_2.m and then add code to your script to call it (and then save and run your script):
[sineVals, expVals] = exp_of_sin_2(angle)
Review the contents of the
to see that you now have two separate variables, sineVals with the sine of each value and expVals with the exponential of the sine of each value.function final_percent = calcPercent( exams, quizzes, hws, labs ) % CALCPERCENT Computes a weighted percentage for the grade % components entered. % % AUTHOR: Beck Hasti % % exams is a vector of exam scores with a max of 60 pts per exam % quizzes is a vector of quiz scores with a max of 10 pts per quiz % hws is a vector of homework scores with a max of 5 pts per hw % labs is a vector of lab scores with a max of 2 pts per lab % % final_percent = exams*60% + quizzes*13% + homeworks*15% + labs*12%
Note that all you've entered so far is the function header and the comments describing what the function is supposed to do. You will now need to create the function body by adding the code that actually does the computation described in the comments.
Create a new section in your teamLab5 script to test your calcPercent function adding the following comment (after the code that is already there):
%% Test calcPercent
Put a clear command after the comment.
Make sure to run your script after each line of code you enter to check what value your calcPercent is returning.
Tip: because you've added a section to your script (with the %% comment), you can run just the code in the Test calcPercent section (and not the entire script): make sure the cursor is somewhere inside the Test calcPercent section; then, instead of selecting
from the ribbon, selectShow your calcPercent function and results of your test script to a lab leader.
It is possible to publish functions to HTML (or PDF) just like you did with the script from Team Lab 4. In this course, you will not be required to publish your functions. Instead, we will require you to turn in your function m-files so that we can run our test scripts with your functions.
4. More complex and realistic functions
The previous examples of sine and exponential are familiar but they have no physical meaning. Following is a formula for the reaction rate of thermonuclear fusion between the hydrogen isotopes of deuterium and tritium as a function of their temperature measured in units of keV. This formula is valid for 1<T<25 keV. Don’t be concerned about the meaning of it, it could as easily be a formula for chemical reactions or combustion reactions.
Define a new MATLAB function that returns the results of this calculation when value(s) of T are provided as input. Name the function DT_reaction_rate. The function header is:
function rr = DT_reaction_rate(T)
Test your new function by entering the following in the
.>> DT_reaction_rate(4)
The result should be 5.1183e-18
If this is not the result, debug your function's formula before proceeding.
Now evaluate the formula for values of T between 1 and 25 in increments of 0.1. Be sure to use a (;) after entering the commands so you don’t get a lot of output in the
What happens? Do you get an error message? If you do, it is probably because the arithmetic operators in the function DT_reaction_rate are trying to do matrix arithmetic. This is not what you want. Use element-wise operators so that they do their computation on each element of the input vector and do not try to do matrix arithmetic. Plot the results that you obtained.
We now wish to compute the fusion power density produced by combining deuterium and tritium together and heating them to high temperatures like 1 to 25 keV. Write another function named DT_fusion_power that evaluates the following formula.
where nD and nT are the densities of the deuterium and tritium reactants measured in atoms / cm3.
The function header for the fusion power function is:
function power = DT_fusion_power( nD, nT, T )
As you enter the formula for power, note that DT_reaction_rate(T) replaces the expression in the formula above. So now you have a function calling another function. This is modular programming! Modular programming is where one programming unit (function) calls another programming unit to solve an even bigger problem. Very complex problems are solved by combining the solutions of many smaller problems.
In the
enter>> DT_fusion_power( 2.7e19, 2.7e19, 4 )
You should get the result 2.0895e+09
These reactant densities are gas densities at atmospheric pressure and the power density is 2 Megawatts per cubic centimeter!!! Notice that you can write functions that have several input quantities. This function has three inputs and the reaction rate function has only one input.
Show your results to a lab leader.
Additional calcPercent functionality:
Modify the calcPercent function so that the lowest quiz and team lab scores get dropped (i.e., are not counted in the grade calculation). To make things a bit simpler, you may assume that there are always at least two team lab scores and two quiz scores. Note that MATLAB has built-in functions like min and max that may be of use (and that structured programming constructs like if or loops are not needed).
Additional challenge: Modify calcPercent so that
- it takes an additional parameter: the zyBook percentage (a value between 0 and 100)
- homeworks are now worth 10% of the grade and zyBook is worth 5%
- full credit for the zyBook portion is given for a percentage of 80 or above
- zyBook credit is pro-rated for percentages less than 80, for example, if the student's zyBook percentage is 40, because 40 out of 80 is 50%, the student would get 50% of the zyBook credit (or 2.5 out of 5)
As before, you may only use built-in MATLAB commands and what you have learned about matrices and vectors so far (e.g., no structured programming constructs).
Concluding remarks: Being able to define your own functions is at the core of all functional programming. A common technique for solving large and complex problems is to break them into smaller problems that can be solved independent of the larger problem. Each smaller problem is likewise solved and code written to accomplish that task. Once all of the smaller problems are solved (and their solutions are tested), we can then solve the larger problem by calling each functional part of the larger solution in the correct sequence.
Good modularization of our solutions often means that our functions are useful for other problems and can thus be reused in different ways to solve different problems. Can you think of any large problems that you were able to solve by breaking into smaller problems? What are the pros of defining a function instead of simply typing that code into the "main" solution script? What are the cons of defining functions?