6.10: Common Mistakes and Best Practices

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    Read aloud

    How

    Speed: 1×
    Light up
    Highlight

    Symbols: Mulberry Symbols, © 2018–2026 Steve Lee, CC BY-SA 4.0 (licence, the set), the site's own copies.

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

    6.10: Common Mistakes and Best Practices

    Infinite Loops

    An infinite loop occurs when the loop condition never becomes false. For example:

    x = 1;
    while x < 10
        disp(x)
    end
    

    This loop will keep displaying 1 because x never changes. A corrected version would update x inside the loop:

    x = 1;
    while x < 10
        disp(x)
        x = x + 1;
    end
    

    Off-by-One Errors

    An off-by-one error happens when a loop runs one too many or one too few times. For example, if a vector has n elements, the valid indices are 1 through n. A loop such as for i = 1:n is usually correct. A loop such as for i = 0:n will cause problems in MATLAB because MATLAB indexing starts at 1, not 0.

    Changing the Loop Variable Inside a for Loop

    It is usually not a good idea to manually change the loop variable inside a for loop. MATLAB automatically updates it. Changing it manually can make your code confusing and may not behave the way you expect.


    This page titled 6.10: Common Mistakes and Best Practices was last modified on Tue, 30 Jun 2026 02:11:42 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.