CS310 Team Lab # 5
Functions and Plotting in MATLAB
Unit 2: Intro to MATLAB & Numeric Computation

PROBLEMS

1. Use MATLAB's Command Window to compute each of these results.

  1. What is the decimal approximation of sine of pi over three? How do you enter the value π in MATLAB?
  2. What is the exponential of the sine of pi over three?  Compute the exponential of the result from part a.  Use the default variable name that MATLAB assigned or repeat the previous command and assign the result to a variable. Repeat the calculation on a calculator to check the results.
  3. Compute the exponential of the sine of a range of angles from 0 to pi over three in (pi over three/100) increments.

    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.

    1. Use the colon operator ( : ) to create a vector of values that ranges from 0 to pi over three in increments of (pi over three/100) and assign the vector result to the variable named vec.
    2. Compute the sine of that vector and save it as sin_vec.
    3. Compute the exponential of the vector result and save it as exp_vec.

    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 Workspace window.  The Variables window shows the contents of each variable you select.

  4. Enter the following commands in the Command Window and compare each result with the contents of vectors vec, sin_vec, and exp_vec, respectively.  Determine and describe to each other what the parenthesis notation in each statement means.

    >> val1 = vec(2)
    >> val2 = sin_vec(1:5)
    >> val3 = exp_vec(2:3:20)

  5. Enter the following statements which clear all current variables and recompute values for the range of angles from 0 to two pi.  Use the semi-colon to suppress the output of these commands.

    >> 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?

  6. Enter the following command to plot sin_vec vs. vec as red circles.

    >> 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 Figure 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 Command Window 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.

  1. On your computer where you are saving your work for CS 310, create a new folder named TeamLab5. You will save the new function definitions that you define for this team lab here.

  2. Create a new MATLAB function file by selecting the menu option New→Function (on the HOME tab). Dock the Editor window, if it is not already docked.  A quick and easy way to do this is to type Ctrl+Shift+D (alternatively, you can find the Dock Editor option by selecting the Show Editor Actions icon, Show Editor Actions icon, in the upper-right corner of the Editor window to the right of the ? icon). Edit or enter the following lines into the Editor 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 Save icon (on the HOME tab).  Be sure to navigate to the MATLAB folder you created in part a and save the file in that folder.

  3. 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 Command Window is the address bar. The address bar shows MATLAB's current working directory and the Current Folder 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 TeamLab5 folder (and you can see exp_of_sin.m in the Current Folder), then you're set. If not, navigate within MATLAB (e.g., using the address bar), to your TeamLab5 folder.

    In the Command Window, 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.

  4. Modify (and save) the function definition by changing the last line to

     results = [ s_val , e_val ];

    In the Command Window, 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.)

  5. Modify (and save) the function definition by changing the last line to

              results = [ s_val ; e_val ];

    In the Command Window, use the up arrow button to repeat the previous command.
    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.

  6. Create a script to test your exp_of_sin function: create a new (empty) script by selecting New Script on the HOME tab, or by selecting New→Script on the HOME tab or the EDITOR 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.

  7. 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.

  8. 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.

  9. 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.

  10. 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 Workspace 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.

3. Grade Percentage Function

  1. Define a function named calcPercent that computes a weighted percentage based on several vectors of scores passed as arguments to the function. The function must be named calcPercent; must use sum() and length() and not mean(); and the function header must be as follows:
    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.

  2. 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.

  3. Next add code to your teamLab5 script to test your function:
    1. Test your function with these values.
      • calcPercent( 0, 0, 0, 0 )
      • calcPercent( 60, 10, 5, 2 )
      • calcPercent( 48, [10 9.5 6.8 9.8 10], [5 5 4.5 3.5 3 5], [2 2 2 2 2] )

      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 Run from the ribbon, select Run Section

    2. Calculate the percent for a student with the scores given below. In your teamLab5 script:
      1. create a vector for each type of grade component:
        • exam scores: 54, 42, 48
        • quiz scores: 10, 9.5, 10, 10, 7.8, 6.5, 8.5, 7, 10, 9.2, 4.5, 8.75
        • homework scores: 5, 5, 4, 5, 5, 3, 4, 5, 4.5, 4, 4, 5, 5, 4.5, 4
        • lab scores: 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
      2. add code to your teamLab5 script to call your calcPercent function and save the results in a new variable.
      3. add code to your teamLab5 script to display your result value in a statement like: The final grade percentage is 84.4229%

    Show 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.

fusion power formula

  1. 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)

  2. Test your new function by entering the following in the Command Window.

              >> DT_reaction_rate(4)

    The result should be         5.1183e-18
    If this is not the result, debug your function's formula before proceeding.

  3. 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 Command Window.  Assign this result to a variable like DTrr.

    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.

  4. 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.

    fusion power 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 reaction rate term 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.

  5. In the Command Window 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 PROBLEMS or FURTHER READING

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

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?