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