Ron Bakker/MathLabHelp
Open MathLab ↗

Tutorial · Beginner · 5 min

Your first plot

Make a vector of numbers, plot a function, label it properly and export it — the basic loop you will use for everything else.

  1. Make some numbers

    linspace(a, b, n) gives n evenly spaced numbers from a to b. Leave off the semicolon and MathLab shows the result in the console.

    x = linspace(0, 2*pi, 9)
    Try it ↗
    x = 1×9
           0  0.7854  1.5708  2.3562  3.1416   3.927  4.7124  5.4978  6.2832
  2. Plot a function

    Functions like sin work on every element of a vector at once. plot(x, y) draws the line. Use more points for a smooth curve, and end lines with ; to keep the console quiet.

    x = linspace(0, 2*pi, 200);
    y = sin(x);
    plot(x, y)
    Try it ↗
  3. Make it readable

    Every figure in a paper needs a title and labelled axes. Options like 'LineWidth' come in name–value pairs.

    x = linspace(0, 2*pi, 200);
    plot(x, sin(x), 'LineWidth', 2)
    title('One period of a sine wave')
    xlabel('angle (radians)')
    ylabel('sin(x)')
    grid on
    Try it ↗
  4. Several lines and a legend

    hold on keeps what is already plotted. A style string such as '--' (dashed) or 'r:o' (red, dotted, circles) changes the look. Colours are picked automatically from a colour-blind-safe palette.

    x = linspace(0, 2*pi, 200);
    plot(x, sin(x), 'LineWidth', 2)
    hold on
    plot(x, cos(x), '--', 'LineWidth', 2)
    plot(x, sin(x).^2, ':')
    hold off
    legend('sin x', 'cos x', 'sin² x')
    title('Three related functions')
    grid on
    Try it ↗

    Tip: Hover over the figure to read off coordinates in the bottom-right corner.

  5. Export it

    Use Export in the top bar: PNG for slides, SVG for papers (sharp at any size), CSV for the plotted data. Exports always use a white background, ready for print.

    x = linspace(0, 2*pi, 200);
    plot(x, sin(x), 'LineWidth', 2), hold on
    plot(x, cos(x), '--', 'LineWidth', 2), hold off
    legend('sin x', 'cos x')
    title('Ready for export')
    xlabel('x'), ylabel('y'), grid on
    Try it ↗