CS310 Team Lab # 4
Engineering Cost Analysis in MATLAB
Unit 2: Intro to MATLAB & Numeric Computation

PROBLEMS

1. Use MATLAB's Command Window to answer the following questions or perform the described calculations

  1. How much money will you have after five years, if you have $10,000 and put it in a bank account that pays 4% interest annually?

    Type the following into the Command Window (don't type the >> — that's the command prompt):

    >> F = 10000*(1+0.04)^5

  2. For each interest rate from 4% to 7% in 0.5% increments, how much money will you have after five years, if the same amount is invested?

    Hopefully, you are considering how best to do this many calculations without retyping all of the values needed. Hint: First, enter the interest rates into a single vector of interest rates and save it with the name a and then perform an element-wise calculation using all elements in the vector. Type the following to create the vector using the colon operator:

    >> a = 0.04 : 0.005 : 0.07

    Repeat an earlier computation by using the up arrow until the calculation is at the command prompt and then editing as needed for the new calculation. Find your calculation from part a and change the 0.04 to the name of your vector of interest rates, a.

    >> F = 10000*(1+a)^5

  3. What happened?

    Before we explain the error (which we will do in the next section), let's just fix it. Type a period (.) before the ^ symbol in the expression and press the Enter key. The (.^) is an element-wise operator. It indicates that the power operator needs to occur on each value (element) in the matrix, instead of performing matrix algebra.

2. Matrix algebra in MATLAB

The power operator by itself (^) performs the exponential multiplication as defined by matrix algebra. Let's review matrix multiplication first.

  1. Compute [by hand] the values in the last row (the cells with ?) of the result matrix.

    [1 2;3 4;5 6]*[1 2;3 4]=[7 10;15 22;? ?]

    Show your answers to a Lab Leader

  2. Check your work using MATLAB:

    >> A = [ 1 , 2 ; 3 , 4 ; 5 , 6 ]
    >> B = [ 1 , 2 ; 3 , 4 ]
    >> C = A * B
    >> D = B * A

    Now what happened?
    The error MATLAB produced is due to the fact that MATLAB tried to multiply two matrices with incompatible dimensions. A 3×2 matrix times a 2×2 matrix is defined, but multiplying a 2×2 matrix with a 3×2 matrix is undefined in matrix algebra, so the B*A operation failed.

  3. Add a scalar value to the matrix named a.

    >> one_plus_a = 1 + a

    Now, one_plus_a contains the quantities of each interest rate plus the value 1. The addition of the scalar value to the matrix of interest rate values (1 + a) works fine. This is because the matrix algebra interpretation of a scalar added to a matrix is to add the scalar to each element of the matrix. Try adding two non-scalar matrices with different dimensions and again an error is the result because that operation is undefined in matrix algebra.

    However, when we tried to raise the quantity (1 + a) to the fifth power, MATLAB produced the error because the matrix dimensions were incompatible for the multiplication operation. Matrix algebra does not allow a 1×N matrix to be multiplied by another 1×N matrix. What we really wanted was each element of the matrix to be raised to the fifth power. This is what element-wise operators do. Thus, replacing the ^ with .^ tells MATLAB to perform the calculation on each element.

  4. How does matrix multiplication work for square matrices in MATLAB?

    Define a square matrix (4×4) and name it x. Then, compute x^2 and x.^2 and store the results in the variables x2_matrix_algebra_mult and x2_elementwise_mult, respectively.

    Show your results to a Lab Leader

  5. Which operator ^ or .^ will square each interest rate in our computation?

3. Future Value of Money (Part 2)

  1. Compute and plot the future value of money vs the interest rates we assigned.

    The up arrow will work, but the command we want now is several commands away. Another way to repeat a previously entered command is to drag it from the Command History window into the Command Window. If the Command History window is not visible, under the HOME tab in the main menu select the Layout drop-down menu. Then under the SHOW heading, select Command History → Docked.

    1. Find the future value of money calculation command from part 1.c in the Command History.
    2. Click and drag it to the Command Window.
    3. Edit the command so that it reads FV = instead of F =
    4. Press Enter to execute the statement.
    5. Type the command: disp( [ 'The future value is $' , num2str(FV) , '.' ] )
      Note: The disp function is used to provide more control over the display of output. The num2str function is used to convert a numeric value (FV) to its corresponding string of characters. This is necessary for display with other characters. The square brackets, [ ] , are used to put the character strings into a single matrix of characters.
    6. Press Enter to see a more readable output sentence.
    7. Plot the results by typing plot(a, FV) and pressing Enter.
  2. Change MATLAB's displayed precision

    1. Type pi and press Enter. MATLAB has a built-in constant pi that contains the value of π. How many significant digits are shown? (If you see more than 5, then type format short, press Enter, then re-enter pi)
    2. Type format long and press Enter to show more precision in your answers. Note: You won't see any output after entering this command.
    3. Type pi and press Enter again. Now how many significant digits are shown? Note that the value of pi has not changed. All that has been changed is how many significant digits MATLAB shows us in the Command Window. Typing and executing the command format short will return MATLAB to standard (default) precision display -- but don't do this now; we want to stay in the long-precision format.
  3. Which of the following investment options is the better investment?

    1. Invest $2,500 in a 3 year CD at 5.7% and then reinvest your money for 3 years at 5.3%.
    2. Invest $2,500 in a CD at 5.5% for 6 years.

    Caution: Do not reenter commands if you can easily drag them from the Command History or repeat them with the up arrow key. Be sure to edit as necessary before pressing Enter.

4. Publishing your work (to HTML)

You have solved some problems, but need to present your work and the results to your boss or instructor.  MATLAB has several tools to help publish your solutions to different forms.  In this class, we ask that you publish your first MATLAB homework solution.

Here's how to save your work in an m-file:

  1. Scroll to the top of the Command History and highlight (select) all the commands underneath the date and time stamp for today's lab (don't include the date and time stamp). Note: you may need to hold down the Shift key and use the arrow keys to select multiple lines (instead of the mouse).
  2. Right-click the mouse and select Create Script. This opens a file Editor window with all of your commands in a list.
  3. If the Editor pops up as a separate window (like the Figure window does when you plot something, as opposed to inside the main MATLAB environment like the Workspace or Command Window), dock the Editor window so that it is part of your MATLAB environment. 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).
  4. On your computer, decide where you want to save your work. Create a new folder named TeamLab4 in this location on your computer.
  5. Save the M-file as TeamLab4.m within the TeamLab4 folder. Caution: Don't use special characters or spaces in your file names.  Digits and the underscore character, _ , are okay as long as they are not the first character in the file name.

Here's how to publish your work (to HTML) using MATLAB:

  1. Download (save) this image file Time value of money formula: F = P*(1+a)^n to your TeamLab4 folder.
    You can do this by right-clicking and selecting Save Image As or Save Picture As.
  2. Add this file header as the first two lines of the TeamLab4.m file and, if you have a line in your script with the date/time stamp, remove it. (A file header is information that is placed at the very beginning of the contents of the file.) You will need to type the blank space between %% and Team Lab 4 for the file header to by published correctly.

    %% Team Lab 4
    % <<../tvom_formula.gif>>

  3. Press F5 (or click the green Run icon in the EDITOR tab) to run your script.  Click Change Folder if prompted to change to the current folder.
  4. Fix any errors in your program script (Editor window). Basically, all of the errors we generated earlier in this lab will now have to be removed or commented out (by putting a % before the line) from your script.
  5. Go to the PUBLISH tab in the menu bar and click the Publish icon.

Now, let's make our work more user-friendly by adding some cell headers and comments. Be sure to edit, remove, or comment out commands that were errors or duplicates from the original command (code) list.

  1. Add the following cell headers before the appropriate lines of code in your M-file. (It's fine to copy-paste them.)
    Don't omit the single blank space after the %% and before the label or the section headers will not be created correctly.

    %% 1.a Numeric Calculations
    %% 2.b Matrix Multiplication
    %% 2.c Add a scalar to a matrix
    %% 2.d Matrix Squared vs Element-wise operator
    %% 3.a Plot the Future Value of Money vs Interest Rate
    %% 3.b Change MATLAB's displayed precision
    %% 3.c Investment Option

  2. Save the file, publish to HTML, and view the results. 
    Notice how each cell header has become a bold heading with a link at the top of the page. If it has not, review the details in the previous steps to trouble-shoot the cause. You will use cell headers to identify each part of your MATLAB homework solutions.
  3. Remove or edit any commands that caused errors.
  4. Save, publish, and view the results.
  5. Delete and edit commands and headers to make your published work easier to read and follow.
  6. Add single line comments (%) immediately after cell headers and within code to answer questions (in 2.e and 3.c), describe what the code is doing, and outline steps in your calculations.
  7. Save, publish, and view the results.
  8. Show a lab leader your work and ask for tips to improve the readability.

5. Publishing multiple plots

When your work requires multiple plots, you will want to make sure the all the plots show up in your published HTML page. One way to do that is to make sure that each plot is in its own cell division before publishing to HTML.  Otherwise, only the last plot will be displayed on the final html page.

Add a new section (i.e., a new cell division) to your program script and add this command to plot the first row of your squared x matrix. Note: this command will only work if you named matrices as directed in earlier steps.

>> plot(x(1,:),x2_elementwise_mult(1,:));

Next, save and run your program. How many plots do you get?

Now, publish and view the results to confirm that two separate plots are visible.

Note: to have each plot show up separately when you are running your program, put the command figure on a line before each plot command. This will tell MATLAB to make a new Figure window to draw the next plot on.

6. Publish your work to PDF

  1. Edit the Publish Configuration options.
    1. Select Edit Publishing Options... from the drop-down menu under the Publish icon.
    2. In Edit Configurations window that pops up, find the section for Output settings.
    3. Under Output settings, change the Output file format field from html to pdf (note: it doesn't look like a drop-down menu, but it is).
    4. Click the Close button.
  2. Click the Publish icon to publish your work as a PDF file.

7. Find the published files you created

The published files you created are automatically saved for you according to the default configuration settings or those that you edited. If you need to print your work, use File→Print while your published document is showing. If you need to upload a PDF, then you will need to know where the PDF file is located.

  1. Open your MATLAB script in MATLAB.
  2. Select Edit Publishing Options... to open the Edit Configuration dialog.
  3. Record (or remember) the location of the output folder for each configuration option you configured.
  4. Open up a folder view for your computer's file system.
    In Windows, click on the File Explorer icon, File Explorer icon, in the task bar.
  5. Navigate through your file system to find the html folder and files you created.
    This is where you will need to navigate in order to upload your PDF file to Canvas.

Show your published PDF to a Lab Leader.

8. Displaying equations in the published document page

There are lots of things you can do to make your final document a better presentation of your work. One cool thing MATLAB can do is display professionally formatted equations in your page. Even though MATLAB does not allow you to enter equations and solve them, you can display the equations that your work is based on in the final document.

  1. Add these comment lines immediately after the Numeric Calculations cell header in your M-file. Add all three comment lines.

    %
    % $$F = P(1+a)^n$$
    %

  2. Save and publish to view the results.
  3. Create a new cell division and add these lines immediately after its header.

    %
    % $$y = \frac{\sin(x)}{\cos( \frac{\pi}{4} ) }$$
    %
    x = 1:0.1:10;
    y = sin(x)/cos(pi/4);
    figure
    plot(x,y)
    title('sin(x)/cos(\pi/4) vs x');
    xlabel('x');
    ylabel('sin(x)/cos(\pi/4)');

  4. Save and publish to view the results.

Note: This syntax is based on LaTeX syntax for entering equations to be formatted. While there is no guarantee that all LaTeX commands will work the same in MATLAB as in LaTeX, many will and it's worth a try.

9. Displaying lists in the published document

It is easy to display a list of items in a cell comment section. MATLAB can produce bulleted lists and numbered lists.

  1. Add these comment lines immediately after the (top) Page Header cell header in your M-file to create a bulleted list. Add all comment lines.

    %
    % * Name 1
    % * Name 2
    % * Name 3
    %

  2. Save and publish to view the results.
  3. Add these comment lines to create a new cell division and numbered list.

    %% Numbered list example
    % # Launch MATLAB
    % # Create script file
    % # Write MATLAB code
    % # Run script
    % # Save and publish
    % # Print or upload as needed

  4. Save and publish to view the results.

10. Getting HELP!

We have presented a lot of different things to try in MATLAB, but what if you need help while working in MATLAB?  Help is just a click or a few typed characters away.

If you know the name of the command you need:
Type help plot to see help displayed in the Command Window.
Type doc plot to launch the Help browser.

If you don't know the name of the command:
Type doc or click the Help icon, Help icon, near the top of your screen to launch the Help browser and then search for a command or topic that will help you solve the problem.

ADDITIONAL PROBLEMS or FURTHER READING

None this week.