Common MATLAB Mistakes
The mistakes that appear most often in code reviews and debugging sessions, each demonstrated by the script below:
Concept
The mistakes that appear most often in code reviews and debugging sessions, each demonstrated by the script below:
* / ^ instead of .* ./ .^ Use dot operators for element-wise math
Variables that shadow functions (sum, max, length, i)
Rename; clear the variable; check with which name i/j used as loop variables, then as the imaginary unit
Use 1i; name loop variables k, n, idx == on floating-point results Compare with a tolerance Chained comparisons a <= x <= b x >= a && x <= b Integer saturation and rounding Convert to double before arithmetic == on texts of different lengths
Accidental implicit expansion (row + column) Check orientations with size Empty arrays in if conditions Use ~isempty, any, all explicitly NaN propagating through statistics
Remove or flag NaNs; 'omitnan' in MATLAB Others worth knowing: growing arrays in loops, inv(A) * b, forgetting hold on, file handles left open, scripts named like built-ins, relying on the current folder, load without an output, and end of the wrong dimension.
Why It Matters
Most of these produce no error — just wrong numbers. Recognizing them quickly is the difference between minutes and days of debugging.
Syntax
which sum % shows whether "sum" is a variable or a function
clear sum % remove a shadowing variableExample
32.1 Ten mistakes, demonstrated
% 1. * instead of .*
v = [1 2 3];
try
y = v * v;
catch err
fprintf('1. v * v fails: %s -> use v .* v = %s\n', err.message, mat2str(v .* v))
end
% 2. shadowing a built-in function with a variable
sum = 10; %#ok<NASGU> deliberately shadows sum()
try
s = sum([1 2 3]);
fprintf('2. sum([1 2 3]) now indexes the variable: result %s\n', mat2str(s))
catch err
fprintf('2. sum([1 2 3]) fails after "sum = 10": %s\n', err.message)
end
clear sum
fprintf(' after "clear sum": sum([1 2 3]) = %d\n', sum([1 2 3]))
% 3. i and j as loop variables
for i = 1:3, end
z = 2 + 3 * i;
fprintf('3. after a loop over i, 2 + 3*i = %g (not complex!); 2 + 3i = %s\n', z, num2str(2 + 3i))
% 4. floating-point comparison
x = 0.1 * 3;
fprintf('4. 0.1*3 == 0.3 -> %d; abs(0.1*3 - 0.3) < 1e-12 -> %d\n', x == 0.3, abs(x - 0.3) < 1e-12)
% 5. chained comparison
v = 20;
fprintf('5. 11.5 <= v <= 14.8 with v = 20 -> %d (wrong); v >= 11.5 && v <= 14.8 -> %d\n', 11.5 <= v <= 14.8, v >= 11.5 && v <= 14.8)
% 6. integer arithmetic surprises
fprintf('6. uint8(200) + uint8(100) = %d, int32(7)/int32(2) = %d\n', uint8(200) + uint8(100), int32(7) / int32(2))
% 7. compari
…Expected Result
(The wording of error messages differs between MATLAB and Octave, but the behaviour is the same.)
1. v * v fails: operator *: nonconformant arguments (op1 is 1x3, op2 is 1x3) -> use v .* v = [1 4 9]
2. sum([1 2 3]) fails after "sum = 10": sum(3): out of bound 1 (dimensions are 1x1) (note: variable 'sum' shadows function)
after "clear sum": sum([1 2 3]) = 6
3. after a loop over i, 2 + 3*i = 11 (not complex!); 2 + 3i = 2+3i
4. 0.1*3 == 0.3 -> 0; abs(0.1*3 - 0.3) < 1e-12 -> 1
5. 11.5 <= v <= 14.8 with v = 20 -> 1 (wrong); v >= 11.5 && v <= 14.8 -> 0
6. uint8(200) + uint8(100) = 255, int32(7)/int32(2) = 4
7. 'VCU' == 'Gateway' fails: mx_el_eq: nonconformant arguments (op1 is 1x3, op2 is 1x7) -> strcmp gives 0
8. row + column gives a 3x3 matrix, not a 1x3 vector
9. if find(...) with no match is false (empty) - use ~isempty or any
10. mean([12.6 NaN 12.4]) = NaN; mean of valid values = 12.5Best Practices
Read the Code Analyzer warnings in the MATLAB editor (orange underlines) — many of these mistakes are flagged there.
Check size and class of intermediate results when something looks wrong.
Write small test scripts with assert for key functions.
Interview Relevance
High: "what's wrong with this code?" rounds usually include * vs .*, shadowed built-ins, float comparisons and chained comparisons.
Practice Questions
Find three variables in your own code that shadow built-in functions (which helps).
Rewrite a chained comparison bug and a float equality bug correctly.
Show how mean behaves with and without NaN values.
Create an accidental 3×3 matrix from two vectors and fix the orientation.
Quick Quiz
Q1. (Multiple choice) After for i = 1:3, end, the expression 2 + 3*i equals: A) 2 + 3i B) 11 C) An error D) 5 Answer: B (verified).
Q2. (Predict the output) 11.5 <= 20 <= 14.8 Answer: 1 (true) — it evaluates (11.5 <= 20) <= 14.8 (verified).
Q3. (True/False) clear sum deletes the built-in sum function.
Answer: False. It deletes the variable that was shadowing it (verified).
Q4. (Find the bug) idx = find(v > 100); if idx, disp('found'), end never prints for a match at position 0… wait — what's the actual problem?
Answer: Indices start at 1, so there is no position 0; the real issue is that if idx is false when find returns an empty result *and* also when… it isn't — if of a non-empty index vector is true. The robust form is if ~isempty(idx) (or if any(v > 100)), which states the intent explicitly.
Coding Challenge
Fix all bugs in this snippet: for i=1:10, x(i) = i^2; end; if x == 0.3*10, disp('ok'), end; y = x*x;
x = zeros(1, 10); % preallocate
for k = 1:10 % avoid i/j
x(k) = k ^ 2;
end
if any(abs(x - 0.3 * 10) < 1e-12) % tolerance and explicit any()
disp('ok')
else
disp('no element equals 3')
end
y = x .* x; % element-wise product
fprintf('y(end) = %d\n', y(end))