0
0
MatlabHow-ToBeginner ยท 3 min read

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 x and y, which causes errors.
  • Forgetting to use hold on when 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:

OptionDescriptionExample
x, yVectors of data pointsplot(x, y)
'r--'Red dashed lineplot(x, y, 'r--')
'bo'Blue circle markersplot(x, y, 'bo')
'LineWidth', 2Set line thicknessplot(x, y, 'LineWidth', 2)
hold on/offPlot multiple lines on same figurehold 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.