Ron Bakker/MathLabHelp
Open MathLab ↗

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.

  1. Syntax errors while you type

    Open this step: the for loop has no end. The line number turns red, the problem is underlined, and the bar under the editor says what is wrong. Add end on the last line to fix it.

    total = 0;
    for k = 1:5
      total = total + k;
    disp(total)
    Try it ↗
    Error on line 2: 'for' on line 2 has no matching 'end'
  2. Unknown names and quick fixes

    Typos are caught before you run: sinn is not a function. In the Problems tab, click Change to sin to fix it. Unused variables are pointed out too.

    x = linspace(0, 2*pi, 100);
    y = sinn(x);
    unused = 42;
    plot(x, y)
    Try it ↗
    Error on line 2: 'sinn' is not defined — did you mean 'sin'?
  3. 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.

    a = 1:3;
    b = 1:4;
    c = a + b
    Try it ↗
    Error on line 3: Matrix dimensions must agree (1×3 and 1×4)
  4. Breakpoints and stepping

    Click the number of line 5 to set a breakpoint (●), then press Debug (F5). Step forward and back, step into square and out again, and add a watch expression such as total * 2 in the Debug tab.

    function y = square(x)
      y = x.^2;
    end
    
    total = 0;
    for k = 1:4
      total = total + square(k);
    end
    disp(total)
    Try it ↗
    30

    Tip: Keyboard: F5 debug or continue, F10 step, Shift+F10 step back, Shift+F11 step out, Esc stop.