CS310 Team Lab # 1
Engineering Cost Analysis in MATLAB
Numeric Computation

OBJECTIVES

INTRODUCTION

Engineering cost analysis requires decision-making based upon comparison of different financing alternatives.

When you do some work for someone, you expect to get paid. The same is true if you loan money to someone. You expect them to pay you interest for the use of your money. On the other side of the coin (no pun intended), if you need to borrow money, you must pay someone else interest for the use of their money. Rather than doing this transaction individual by individual, society has banks that serve as intermediaries who pay interest for money given to them and who charge interest for money that they loan. Thus in the financial world, money is like labor or goods and services. Businesses that need money must pay for it. This is the way the business and thus the engineering world works.

A general principle that applies to all financial transactions is called the time value of money. A dollar that you have today is worth more in the future because you don’t hide it under your mattress. You invest it in a savings account, certificate of deposit, stock or bond or some other “financial instrument” and your money earns interest. This works because the institution that takes your money immediately loans it to someone else for their use and charges them interest.

The time value of money is computed using the formula: where:

P = the present value of your money
F = the future value of your money after n periods (months or years)
a = the percent interest paid for your money per month or year, and
n = the number of periods (months or years) over which the interest is computed (or compounded)

MatLab is short for Matrix Laboratory. It is a computing environment that makes it easy to perform very complex numeric computations. In numeric computing, we compute initial, intermediate, and final numeric values (numbers) in order to solve problems. This is in contrast with symbolic computing where symbols are used to create expressions and equations and then the equations are manipulated without much thought to the specific underlying value for each symbol.

In numeric computing, the values themselves are needed to find the next step in the solution and the solution is one or more values instead of a symbol or symbolic expression. Note: Variable names are used in MatLab, but they are not abstract symbolic variables as you might see in a math equation. Rather they are more like nicknames for values that have been computed.

Let's get started!

PROBLEMS

1. Use MatLab's Command Window to answer the following question or perform the described calculations

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

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

b. 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.
 >> 10000*(1+a)^5
c. What happened?

Before we explain the error, 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.

a. Compute [by hand] the values for the blank cells of the result matrix.

[1 2;3 4;5 6;7 8]*[1 2 3;4 5 6]=[9 12 15;19 26 __;29 __ __; __ __ __]

b. SHOW YOUR COMPLETED MATRIX TO A LAB LEADER

c. Check your work using MatLab:

>> A = [ 1 , 2 ; 3 , 4 ; 5 , 6 ; 7 , 8 ]
>> B = [  1,  2, 3 ;  4,  5, 6 ]
>> 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 4x2 matrix times a 2x3 matrix is defined, but multiplying a 2x3 matrix with a 4x2 matrix is undefined in matrix algebra, so the B*A operation failed.

b. 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 1xN matrix to be multiplied by another 1xN 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.

c. How does matrix multiplication work for square matrices in MatLab?

Define a square matrix (4x4) and name it x. Then, compute x^2 and x.^2 and save the results as x2_matrix_algebra_mult and x2_elementwise_mult, respectively.

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

3. Future Value of Money (Part 2)

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

  1. Type format long and press Enter to show more precision in your answers. Typing and executing the command format short will return to standard precision display.
  2. Find the future value of money calculation command in the command history.
  3. Click and drag it to the command window.
  4. Edit the command so that it reads FV = instead of F =
  5. Add a semi-colon to suppress the results.
  6. Press Enter to execute the statement without displaying the results.
  7. 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.
  8. Press Enter to see a more readable output sentence.
  9. Plot the results by typing plot(a,FV) and pressing Enter.

Type and enter the clear command. This will undefine (clear) all variable names.

b. 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 homework solutions to HTML or PDF. 

Note: HTML is currently the most common type of web page found on the internet.  If you copy your HTML pages to a computer folder that is available via the internet (on a web server), then you will be able to see your work from anywhere you have internet access.

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

  1. Scroll to the top of the Command History and left-click on the date and time stamp for today's lab.  This highlights all commands executed today.
  2. Right-click the mouse and select Create Script.  This opens a file editor window with all of your commands in a list.
  3. Dock the editor window so that it is part of your MatLab environment. To dock your editor window, click on the small curved arrow icon dock editor button near the close window icon close window button.
  4. Save the M-file as TeamLab1.m  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 to your MATLAB\TeamLab1 folder.
    Right-click and "Save Image As" or "Save Picture As".

  2. Add this file header as the first line of the file and remove the date/time stamp. You will need to type the blank space between %% and Team Lab 1 for the file header to by published correctly.

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


  3. Press F5 to run your script.  Click "Change Directory" if prompted to change to the current directory.
  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 from your script.
  5. Select File -> Publish from the menu bar or find 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 or remove commands that were errors or duplicates from the original command (code) list.

  1. Add the following cell headers before the appropriate lines in your M-file. 
    Don't omit the single blank space after the %% and before the label or you'll not create the section headers correctly.
%% 1.a Numeric Calculations
%% 2.a Matrix Multiplication
%% 2.b Add a scalar to a matrix
%% 2.c Matrix Squared vs Element-wise operator
%% 3.a Plot the Future Value of Money vs Interest Rate
%% 3.b Investment Option
  1. 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.
  2. Remove or edit any commands that caused errors.
  3. Save, Publish, and view the results.
  4. Delete and edit commands and headers to make your published work easier to read and follow.
  5. Add single line comments (%) immediately after cell headers and in code.
  6. Save, Publish, and view the results.
  7. Show a lab leader your work and ask for tips to improve the readability.

5. Publishing multiple plots

When your work requires multiple plots, 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. Try getting two or more plot figures to display on your HTML page.

Add a new section 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,:));

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

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

  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$$
% 
  1. Save and Publish to view the results.
  2. 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); plot(x,y)
title('sin(x)/cos(\pi/4) vs x');
xlabel('x');
ylabel('sin(x)/cos(\pi/4)');
  1. 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.

7. 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.  Add all comment lines.
    % 
    % * Name 1
    % * Name 2
    % * Name 3
    % 
  2. Save and Publish to view the results.
  3. Add these lines Create a new cell division and add these lines immediately after its header.
    %% Numbered list example 
    % # Launch MATLAB
    % # Create Script file
    % # Write MATLAB code
    % # Run script
    % # Save and Publish
    % # Print or Upload as need
  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.

8. Publish your work to PDF. (If you're not using version R2011a, which has a bug that prevents publishing to pdf).

  1. Edit the Publish Configuration options.
    1. Select File->Publish Configuration for ... -> Edit Publish Configurations for ...
    2. Click the [+] and then select Publish configuration
    3. Change the Output file format field to pdf
    4. Click the Close button.
  2. Use the new configuration to publish your work as a pdf.
    Select the File -> Publish configuration for ... - option you just created.

Show your Published PDF to a Lab Leader.

9. 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 are asked to print your work, use File->Print while your published document is showing. If we ask you to upload a PDF, then you will need to know where the pdf file is located.

  1. Open your MATLAB script in MATLAB.
  2. Open the Edit Publish 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.
  5. In Windows, [Right-click] Start->Windows Explorer.

  6. Navigate through your file system to find the html or pdf folder and files you created.
  7. This is where you will need to navigate in order to upload your work to the Dropbox.

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

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

ADDITIONAL PROBLEMS or FURTHER READING

The solution for this lab will be available at 4pm on Thursday. Please review and ask questions before starting the quiz. Be sure to complete Quiz 1.