Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 45 ยท Practice and Review

Common Mistakes and How to Fix Them

Avoid the classic MATLAB and Octave traps: 1-based indexing, column-major order, element-wise operators, size mismatches, shadowed built-ins and float comparisons.

Most MATLAB and Octave bugs come from a short list of surprises, and the same ones catch beginners and experts alike. Some produce an error message, which is the kind one. Others produce a plausible but wrong number, which is the dangerous kind: the program runs, the plot appears, and the result is silently off.

This lesson collects the common traps with a symptom, the cause and the fix for each. MATLAB and Octave do not run in your browser here, so the MATLAB code is read-only, and each trap has a Python stand-in (NumPy) that reproduces the same numbers or the same kind of mistake, so you can try the fix. For the Python-specific side of each trap, see MATLAB, Octave and Python Compared.

Silent bugs

Wrong operator
  • where you meant .*
Wrong order Column-major reshape and linear indexing.
Float equality 0.1 + 0.2 is not 0.3.
Shadowed names A variable named sum hides the function.
1 / 2

Mistake 1: indexing from zero, and going past the end

Symptom: Index in position 1 is invalid. Array indices must be positive integers or logical values. or Index exceeds the number of array elements.

Cause: MATLAB and Octave count from 1. x(0) is always an error, and x(numel(x)+1) reads beyond the end. The reverse happens when a Python habit slips in: a range such as x(1:n-1) silently leaves out the last element, and the Python-style 0:n-1 loop range is an error because of the 0.

Fix: Think "first element is 1, last is end". Use x(end), x(end-1:end) and numel(x) instead of hand-computed lengths. For loops, write for k = 1:numel(x) and never 0:numel(x)-1.

MATLAB
x = [10 20 30];
x(0)          % error: indices must be positive integers
x(4)          % error: index exceeds the number of array elements
x(end)        % 30: always safe
x(end+1) = 40 % assigning past the end grows the vector: x = [10 20 30 40]

Note that assigning past the end is legal and grows the array, which can hide a typo. Reading past the end is an error, as shown in Indexing and Slicing.

Mistake 2: column-major surprises

Symptom: reshape or A(:) returns elements in an order you did not expect, or a loop over a matrix visits the wrong elements.

Cause: MATLAB stores a matrix column by column. Linear indexing A(k), A(:) and reshape all follow that order. Nested loops should therefore have the row index in the inner loop to walk through memory in order.

Fix: Remember that the first column comes first. If you want row order, transpose first: reshape(A.', 1, []).

Python Column-major order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A(2) is 4, the first element of the second column, and not 2, and A(3) is 2, not 3. Linear indexing is useful, but check which order you expect.

Mistake 3: * instead of .*

Symptom: Incorrect dimensions for matrix multiplication (the lucky case), or a result with a different shape than you expected (the unlucky case: two square matrices multiply "successfully" as a matrix product).

Cause: *, / and ^ are matrix operations. Element-wise versions have a dot: .*, ./, .^.

Fix: Decide for each operator whether you mean "multiply matrix-wise" (rare) or "multiply each element" (usual), and add the dot for the second. A formula like y = x^2 + 3*x with a vector x fails; y = x.^2 + 3*x works, because multiplying by a scalar needs no dot.

Python Matrix product versus element-wise product

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The details are in Arithmetic: Matrix vs Element-wise.

Mistake 4: size mismatches and accidental expansion

Symptom: Arrays have incompatible sizes for this operation or, worse, a matrix appears where you wanted a vector.

Cause: Modern MATLAB and Octave use implicit expansion: a row plus a column produces a full table of sums. So adding a 1-by-3 vector to a 3-by-1 vector silently gives a 3-by-3 matrix. A common source is a row from one computation and a column from another.

Fix: Check size(a) and size(b) when a result looks wrong. Force orientation with x(:) (column) or x(:).' (row).

MATLAB
r = [1 2 3];       % 1x3
c = [10; 20; 30];  % 3x1
r + c              % 3x3 matrix, not a vector!
r + c.'            % 1x3 vector: [11 22 33]
Python Row plus column gives a table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Mistake 5: clobbering a built-in function

Symptom: Index exceeds the number of array elements or Array indices must be positive integers on a line that calls sum(x), max(x), length(x) or i, even though that worked yesterday.

Cause: A variable with the same name hides the function. After sum = 0; the name sum is a number, so sum(x) is an attempt to index a scalar with x. The same happens with max, min, mean, size, length, std, diff, abs, data, table, i and j (the imaginary unit).

Fix: Pick different variable names (total, largest, n_items). If it already happened, clear sum removes the variable, and which sum shows what a name currently refers to. Make which -all name a habit when behaviour seems strange.

MATLAB
sum = 0;
for k = 1:5
    sum = sum + k;
end
sum([1 2 3])      % error! sum is now a number
clear sum
sum([1 2 3])      % 6: the function is back

A Python script has the same hazard with sum, max, list and len, and the stand-in below shows it.

Python A variable that hides a built-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Mistake 6: comparing floating-point numbers with ==

Symptom: 0.1 + 0.2 == 0.3 is false, a loop for x = 0:0.1:1 has a different number of steps than expected, or if a == b fails after a calculation that should give equal values.

Cause: Most decimal fractions have no exact binary representation, so tiny rounding errors accumulate (see Numeric Types and Precision).

Fix: Compare with a tolerance: abs(a - b) < 1e-9 or a relative test abs(a - b) <= 1e-9 * max(abs(a), abs(b)). Use eps as the smallest meaningful unit for numbers near 1. For stepping loops, iterate over integers and compute the value: for k = 0:10, x = k/10; .... Use isequal only when exact equality is the intent, such as for integer-valued data.

Python Float equality and tolerances

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Mistake 7: growing arrays in a loop, and forgetting to preallocate

Symptom: Nothing breaks, but a loop that fills a result vector gets slower and slower as it grows. The editor underlines the line with "variable appears to change size on every loop iteration".

Cause: result(end+1) = value may reallocate and copy the whole array, so a loop of n steps does roughly n^2 copying.

Fix: Preallocate with zeros, and better, vectorize the whole loop. This is explained further in Performance and Memory.

MATLAB
n = 1e5;
squares = zeros(1, n);        % preallocate
for k = 1:n
    squares(k) = k^2;
end
squares = (1:n).^2;           % better: no loop at all

Mistake 8: copies, handles and the wrong kind of brackets

Three smaller traps appear often:

  • B = A copies, but only when it must. MATLAB uses copy-on-write: B = A is cheap, and changing B later does not change A. That is the reverse of the NumPy habit described in MATLAB, Octave and Python Compared. The exceptions are handle objects (for example figures and containers.Map), where two names really refer to the same object.
  • c(2) versus c{2} on a cell array. Parentheses return a cell, braces return the contents. c(2) + 1 fails because a cell is not a number. See Cell Arrays.
  • A missing semicolon floods the screen. If a command prints a huge matrix, press Ctrl+C. Add a semicolon to everything inside a loop.
Python Cell versus contents, and an honest list stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A debugging routine

When a result looks wrong, work through this short list before changing anything:

  1. Look at the sizes. size(x), class(x) and whos tell you more than the numbers.
  2. Remove semicolons on the suspicious lines and look at the values.
  3. Run the line on a tiny example whose answer you can work out by hand.
  4. Ask which name if a function call acts strangely: a shadowing variable or a file with the same name in the current folder is the usual culprit.
  5. Use the debugger: dbstop if error and look at the workspace at the failing line (see Errors, Warnings and Debugging).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After the statement sum = 0, what does sum([1 2 3]) do?

    A variable hides the function of the same name. clear sum brings the function back, and better names avoid the problem.
  2. 2. For A = [1 2 3; 4 5 6], what is A(3)?

    Linear indexing follows column-major order: 1, 4, 2, 5, 3, 6. The third element in that sequence is 2.
  3. 3. How should you test whether two computed floating-point numbers are equal?

    Rounding errors make exact equality unreliable. A tolerance expresses what 'equal enough' means.
  4. 4. What is r + c if r is 1x3 and c is 3x1?

    Implicit expansion stretches the row and column into a full table of sums. Transpose one of them if you wanted element-by-element addition.
  5. 5. Why is result(end+1) = value inside a long loop a problem?

    Growing an array repeatedly can copy it each time. Preallocating with zeros, or vectorizing, avoids that cost.

Summary

  • Indexing starts at 1; read past end and you get an error, assign past it and the array silently grows.
  • MATLAB and Octave are column-major: A(:), linear indexing and reshape run down the columns.
  • *, / and ^ are matrix operations; use .*, ./ and .^ for element-wise work.
  • Row plus column expands to a matrix; check size when a result has an unexpected shape.
  • Never name a variable sum, max, length, i and so on; clear name and which name repair and diagnose a shadowed function.
  • Compare floats with a tolerance, preallocate arrays, and use {} for contents versus () for sub-cells.

Next, test yourself with Practice Exercises with Solutions.