8.8: 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.

    8.8: Common Mistakes and Best Practices

    Mixing Up {} and ()

    This is the most common cell array mistake. If MATLAB gives an error that seems related to data type, check whether you used curly braces or parentheses.

    C = {42, 'hello'};
    
    a = C{1};    % a is the number 42
    b = C(1);    % b is a 1-by-1 cell array

    If a function expects a number, you probably need C{1}, not C(1).

    Forgetting the Element Number in a Structure Array

    If packages is a structure array, packages.price refers to the price field across the array, not necessarily a single value. If you want the price of the second package, write:

    packages(2).price

    Using Inconsistent Field Names

    MATLAB field names are case-sensitive. This means GPA and gpa are different field names.

    student.GPA = 3.8;
    student.gpa = 3.9;   % This creates a different field

    Choose one naming style and use it consistently.

    Trying to Delete One Cell from a 2D Cell Array

    A 2D cell array must stay rectangular. You can delete a whole row or column, but not one cell in the middle.

    C(:,2) = [];   % Delete column 2
    C(3,:) = [];   % Delete row 3

    Confusing Table Indexing Methods

    Table indexing has its own version of the curly-brace versus parentheses issue. Parentheses return a table. Curly braces return the data inside the table. Dot notation returns one variable by name.

    T(:, "GPA")     % returns a table
    T{:, "GPA"}     % returns the GPA values
    T.GPA           % also returns the GPA values

    If MATLAB gives an error while doing math with table data, check whether you accidentally kept the result as a table when you meant to extract the numeric values.


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