5.1: Name Collisions

Physical Modeling in MATLAB · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    5.1: Name Collisions

    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, total, i, and a.

    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.


    This page titled 5.1: Name Collisions was last modified on Thu, 17 Nov 2022 18:18:39 GMT and is shared under a CC BY-NC 4.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.