5.1: Name Collisions
- Page ID
All scripts run in the same workspace, so if one script changes the value of a variable, all other scripts see the change. With a small number of simple scripts, that’s not a problem, but eventually the interactions between scripts become unmanageable.
For example, the following script computes the sum of the first
n terms in a geometric sequence, but it also has the side effect of assigning values to
A1 = 1; total = 0; for i=1:10 a = A1 * 0.5^(i-1); total = total + a; end ans = total
If you were using any of those variable names before calling this script, you might be surprised to find, after running the script, that their values had changed. If you have two scripts that use the same variable names, you might find that they work separately and then break when you try to combine them. This kind of interaction is called a name collision.
As the number of scripts you write increases, and they get longer and more complex, name collisions become more of a problem. Avoiding this problem is one of several motivations for functions.