Skip to main content

Introduction

Figure 9.0.1. Type, type, type.
To start this chapter I would like you to consider a situation where you need to perform the same calculation with different numbers multiple times. For example, let’s pretend that you are preparing for a final exam, and you would like to know how different final exam grades will impact your overall average. You have already taken midterm 1, midterm 2, and midterm 3 so those grades are locked. You recall that to calculate the average all you have to do is sum your values and divide the sum by the number of entries. For you math folks, the formula is:
\(average= \frac{1}{n} \sum_{i=1}^{n} a_i\)
Your MATLAB code might look something like this. Feel free to type this into the MATLAB command window yourself, it is good practice).

Example 9.0.2. Test Computing the Average of Your Three Exams.

Here is an interactive code box that functions identically to the MATLAB command window.
Note: there are actually even better and more clever ways of performing this exact same calculation in MATLAB but for now, let’s stick with this example.
Figure 9.0.3. Example of workspace variables
Viola! You can see that your average exam score would be 87.75. Now let’s consider how a 75 on the final would affect the average exam score. We can see that the variables for the var scores are still present in the workspace (Figure 9.0.3 above). All we need to do is overwrite the final exam score so that it is 75, then re-run the average exam score calculation.

Example 9.0.4. Test Computing the Average of With a New Final Grade.

Here is an interactive code box that functions identically to the MATLAB command window.
Hint, you can hit the up arrow key on your keyboard to bring up your recent command history to select the previous line of code so you don’t need to retype it! This is a valuable tool to remember.
Figure 9.0.5. Updated workspace variables.
At this point, you can see that your average_exam_score variable has been updated to the value of 83.75. If you were following along, the variables in your workspace should look like this (Figure 9.0.5 above).
Here is the problem. If you close MATLAB and reopen it all of those variables are lost (technically you could recover them from your command history but that is a hassle). What happens if we want to re-calculate your grade to see what would happen if you get a 95 on the final? You would have to retype all of those lines back in! Clearly, that is not very efficient. The power in MATLAB and most scripting programming languages is that you can make a script that can be changed and re-run with whatever variables you choose. The script is just a linear series of commands that MATLAB executes stored in a file with a .m extension.
In this chapter, we will expand on the previous chapter to show you the real power of MATLAB. We will learn: