How to Use Plot Function in MATLAB: Simple Guide
In MATLAB, use the
plot function to create 2D line graphs by passing vectors of x and y data points like plot(x, y). You can customize the plot with colors, markers, and line styles by adding extra arguments.Syntax
The basic syntax of the plot function is:
plot(y): Plots y versus its index.plot(x, y): Plots y versus x.plot(x, y, 'LineSpec'): Plots with specified line style, marker, and color.plot(x1, y1, x2, y2, ...): Plots multiple lines on the same graph.
Here, x and y are vectors of the same length, and 'LineSpec' is a string like 'r--' for red dashed line.
matlab
plot(x, y)
plot(x, y, 'r--')
plot(y)
plot(x1, y1, x2, y2)Example
This example shows how to plot a sine wave with blue circles connected by lines. It demonstrates basic plotting and customization.
matlab
x = linspace(0, 2*pi, 100); y = sin(x); plot(x, y, 'bo-') title('Sine Wave') xlabel('x values') ylabel('sin(x)') grid on
Output
A 2D line plot with blue circle markers connected by lines showing one full sine wave cycle from 0 to 2ฯ.
Common Pitfalls
Common mistakes when using plot include:
- Passing vectors of different lengths for
xandy, which causes errors. - Forgetting to use
hold onwhen plotting multiple lines separately. - Using incorrect
'LineSpec'strings that MATLAB does not recognize. - Not labeling axes or adding titles, making plots hard to understand.
matlab
x = 1:5; y = [2, 3, 4]; % Different length plot(x, y) % This will cause an error % Correct way: y = [2, 3, 4, 5, 6]; plot(x, y) % Plotting multiple lines without hold on (overwrites): plot(x, y) plot(x, y+1) % Only last plot shows % Correct way: plot(x, y) hold on plot(x, y+1) hold off
Quick Reference
Here is a quick summary of common plot options:
| Option | Description | Example |
|---|---|---|
| x, y | Vectors of data points | plot(x, y) |
| 'r--' | Red dashed line | plot(x, y, 'r--') |
| 'bo' | Blue circle markers | plot(x, y, 'bo') |
| 'LineWidth', 2 | Set line thickness | plot(x, y, 'LineWidth', 2) |
| hold on/off | Plot multiple lines on same figure | hold on; plot(x, y1); plot(x, y2); hold off |
Key Takeaways
Use plot(x, y) to create 2D line graphs with x and y data vectors.
Customize plots with line styles and markers using the 'LineSpec' string.
Ensure x and y vectors have the same length to avoid errors.
Use hold on to plot multiple lines on the same figure.
Always label axes and add titles for clarity.