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.
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.
Try it ↗x = linspace(0, 2*pi, 9)x = 1×9 0 0.7854 1.5708 2.3562 3.1416 3.927 4.7124 5.4978 6.2832Plot a function
Functions like
sinwork 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.
Try it ↗x = linspace(0, 2*pi, 200); y = sin(x); plot(x, y)Make it readable
Every figure in a paper needs a title and labelled axes. Options like
'LineWidth'come in name–value pairs.
Try it ↗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 onSeveral lines and a legend
hold onkeeps 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.
Try it ↗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 onTip: Hover over the figure to read off coordinates in the bottom-right corner.
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.
Try it ↗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