Tutorial · Beginner · 8 min
Finding and fixing mistakes
MathLab checks your code as you type, explains errors in plain language, and can replay a run step by step.
Syntax errors while you type
Open this step: the
forloop has noend. The line number turns red, the problem is underlined, and the bar under the editor says what is wrong. Addendon the last line to fix it.
Try it ↗total = 0; for k = 1:5 total = total + k; disp(total)Error on line 2: 'for' on line 2 has no matching 'end'Unknown names and quick fixes
Typos are caught before you run:
sinnis not a function. In the Problems tab, click Change to sin to fix it. Unused variables are pointed out too.
Try it ↗x = linspace(0, 2*pi, 100); y = sinn(x); unused = 42; plot(x, y)Error on line 2: 'sinn' is not defined — did you mean 'sin'?Errors when running
Some mistakes only show up when the code runs, like adding vectors of different lengths. The console explains the problem and the line is highlighted. Click Debug this error to see every variable at that moment.
Try it ↗a = 1:3; b = 1:4; c = a + bError on line 3: Matrix dimensions must agree (1×3 and 1×4)Breakpoints and stepping
Click the number of line 5 to set a breakpoint (●), then press Debug (F5). Step forward and back, step into
squareand out again, and add a watch expression such astotal * 2in the Debug tab.
Try it ↗function y = square(x) y = x.^2; end total = 0; for k = 1:4 total = total + square(k); end disp(total)30
Tip: Keyboard: F5 debug or continue, F10 step, Shift+F10 step back, Shift+F11 step out, Esc stop.