MATLAB Tutorial

Plotting

Visualizing data in 2D and 3D with MATLAB

Creating Your First Plot

MATLAB is famous for its simple and powerful plotting commands. To create a basic line plot, you just need the plot() function.
matlab
x = 0:0.1:10;
y = sin(x);
plot(x, y)

Customizing the Plot

Wait! You can add labels, titles, and legends in just a few lines.
matlab
title('Sine Wave')
xlabel('Time (s)')
ylabel('Amplitude')
grid on

Multiple Data Sets

To add a second line to the same chart, use the hold on command.
matlab
plot(x, sin(x))
hold on
plot(x, cos(x), 'r--') % Red dashed line
legend('Sine', 'Cosine')

Common Plot Types

FunctionDescription
plot2D Line plot
scatterScatter plot
barBar chart
histogramFrequency distribution
piePie chart
surf3D Surface plot (Very famous in MATLAB!)
contour2D Contour plot

3. Subplots

You can display multiple charts in a single window using subplot(rows, cols, index).
matlab
subplot(2, 1, 1); plot(x, y1);
subplot(2, 1, 2); plot(x, y2);

Summary

TermDescription
figureOpen a new plot window
clfClear the current figure
axisSet the axis limits
gridTurn on/off the grid lines
saveasSave the plot to a file (PNG, PDF, etc.)
Best ForVisualizing scientific data and engineering results
Logic"Visualize as you calculate"
SafetyHigh-precision rendering of mathematical functions
ModernThe plot command has been optimized for billions of data points
StandardUse xlabel, ylabel, and title on every professional plot
IdentityThe "Surface Plot" is the iconic image of MATLAB