How to Use Subplot in MATLAB: Syntax and Examples
Use
subplot(m, n, p) in MATLAB to divide the figure into an m by n grid and place the plot in the p-th position. This lets you display multiple plots in one window easily.Syntax
The subplot function divides the figure window into a grid of m rows and n columns. The third argument p specifies the position of the current plot in this grid, counted column-wise from left to right, top to bottom.
- m: Number of rows in the grid
- n: Number of columns in the grid
- p: Position index of the subplot (1 to m*n)
matlab
subplot(m, n, p)
Example
This example creates a figure with 2 rows and 2 columns of plots. Each subplot shows a simple plot with different data.
matlab
x = 1:10; subplot(2, 2, 1) plot(x, x) title('Plot 1: y = x') subplot(2, 2, 2) plot(x, x.^2) title('Plot 2: y = x^2') subplot(2, 2, 3) plot(x, sqrt(x)) title('Plot 3: y = sqrt(x)') subplot(2, 2, 4) plot(x, log(x)) title('Plot 4: y = log(x)')
Output
A figure window opens showing 4 plots arranged in a 2x2 grid with titles as described.
Common Pitfalls
Common mistakes when using subplot include:
- Using a
pvalue larger thanm*n, which causes an error. - Not calling
subplotbefore each plot, which overwrites the previous plot. - Confusing the order of
m,n, andp.
Always specify subplot before plotting to place the plot in the correct grid cell.
matlab
subplot(2, 2, 5) % Wrong: position 5 does not exist in 2x2 grid plot(1:10) % Correct way: subplot(2, 2, 1) plot(1:10)
Output
Error: Index exceeds matrix dimensions for the first plot command; second plot displays normally in first subplot.
Quick Reference
| Function | Description |
|---|---|
| subplot(m, n, p) | Create a grid of m rows and n columns, activate p-th subplot |
| plot(x, y) | Plot data in the current subplot |
| title('text') | Add title to the current subplot |
| clf | Clear current figure window |
| figure | Create new figure window |
Key Takeaways
Use subplot(m, n, p) to divide the figure into a grid and select the plot position.
Always call subplot before plotting to avoid overwriting plots.
The position p counts left to right, top to bottom starting at 1.
Ensure p does not exceed m*n to prevent errors.
Use titles and labels to clearly identify each subplot.