Let’s review the sequence of steps that occur when you call a function:
- Before the function starts running, MATLAB creates a new workspace for it.
- MATLAB evaluates each of the arguments and assigns the resulting values, in order, to the input variables (which live in the new workspace).
- The body of the code executes. Somewhere in the body a value gets assigned to the output variable.
- The function’s workspace is destroyed; the only thing that remains is the value of the output variable and any side effects the function had (like displaying values).
- The program resumes from where it left off. The value of the function call is the value of the output variable.
When you’re reading a program and you come to a function call, there are two ways to interpret it. You can think about the mechanism I just described, and follow the execution of the program into the function and back, or you can assume that the function works correctly, and go on to the next statement after the function call.
When you use a built-in function, it’s natural to assume that it works, in part because you don’t usually have access to the code in the body of the function. But when you start writing your own functions, you might find yourself following the “flow of execution.” This can be useful while you are learning, but as you gain experience, you should get more comfortable with the idea of writing a function, testing it to make sure it works, and then forgetting about the details of how it works.
Forgetting about details is called abstraction; in the context of functions, abstraction means forgetting about how a function works and just assuming (after appropriate testing) that it works. For many people, it takes some time to get comfortable with functions. If you are one of them, you might be tempted to avoid functions, and sometimes you can get by without them.
But experienced programmers use functions extensively, for several good reasons. First, each function has its own workspace, so using functions helps avoid name collisions. Functions also lend themselves to incremental development: you can debug the body of the function first (as a script), then encapsulate it as a function, and then generalize it by adding input variables.
Also, functions allow you to divide a large problem into small pieces, work on the pieces one at a time, and then assemble a complete solution.
Once you have a function working, you can forget about the details of how it works and concentrate on what it does. This process of abstraction is an important tool for managing the complexity of large programs.