2.10: Common Mistakes and Best Practices

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    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.

    2.10: Common Mistakes and Best Practices

    Use the following best practices when writing scripts and functions.

    • Run your script in a debug mode often while you are writing it. Do not wait until the entire program is finished.
    • Use semicolons to suppress output, but temporarily remove them when you want to inspect a variable.
    • Check spelling carefully. MATLAB treats area, Area, and AREA as different names.
    • Make sure function file names match function names.
    • If MATLAB says a function is undefined, check that the file is saved in the current folder or on the MATLAB path.
    • Read error messages from the top. MATLAB often tells you the file name and line number where the problem occurred.
    • Use comments to explain why you wrote a step, not just what the command already says.

    Common Beginner Mistakes

    Mistake

    Why it happens

    How to fix it

    Forgetting .m extension when saving

    The file may not be recognized as a MATLAB script or function.

    Save scripts and functions with the .m extension.

    Using spaces in file names

    MATLAB function and script names should not contain spaces.

    Use names like rectangleArea.m instead of rectangle area.m.

    Forgetting text input option

    input tries to evaluate text as a variable.

    Use input('Prompt: ', 's') for text input.

    Function name does not match file name

    MATLAB searches for a file with the function name.

    Save calcArea as calcArea.m.

    Using disp when formatted output is needed

    disp cannot easily combine text and formatted numbers.

    Use fprintf with format operators.

    Forgetting
    in fprintf

    The next output may appear on the same line.

    Add
    at the end of the message.

    Units are mixed

    Values may be entered in different unit systems.

    Write prompts and comments that clearly state units.


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