19.1: Functions and Files
- Page ID
So far we’ve only put one function in each file. It’s also possible to put more than one function in a file, but only the first one, the top-level function, can be called from the Command Window. The other helper functions can be called from anywhere inside the file, but not from the Command Window or any other file.
Keeping multiple functions in one file is convenient, but it makes debugging difficult because you can’t call helper functions from the Command Window.
To help with this problem, I often use the top-level function to develop and test my helper functions. For example, to write a program for Section 7.2, I would create a file named duck.m and start with a top-level function named
duck that takes no input variables and returns no output value.
Then I would write a function named
error_func to evaluate the error function for
fzero. To test
error_func, I would call it from
duck and then call
duck from the Command Window.
Here’s what my first draft might look like:
function res = duck() error = error_func(10) end function res = error_func(d) rho = 0.3; % density in g / cm^3 r = 10; % radius in cm res = d; end
This program is not complete, but it is enough code to test. Once this program is working, I would finish writing
error_func. And once I’d finished and tested
error_func, I would modify
duck to use
This problem might only require two functions, but if there were more, I could write and test them one at a time and then combine them into a working program.
Now, let’s get back to differential equations.