How to Create Plot in MATLAB: Simple Steps and Examples
To create a plot in MATLAB, use the
plot(x, y) function where x and y are vectors of data points. This function draws a 2D line graph connecting the points defined by x and y.Syntax
The basic syntax for creating a plot in MATLAB is plot(x, y), where x is a vector of x-coordinates and y is a vector of y-coordinates. You can also add optional arguments to customize the line style, color, and markers.
- x: Vector of x-axis data points.
- y: Vector of y-axis data points.
- LineSpec (optional): String to specify line style, marker, and color (e.g., '-r' for red solid line).
matlab
plot(x, y)
plot(x, y, 'LineSpec')Example
This example shows how to plot a sine wave using MATLAB's plot function. It creates x values from 0 to 2ฯ and plots their sine values.
matlab
x = linspace(0, 2*pi, 100); y = sin(x); plot(x, y, '-b') title('Sine Wave') xlabel('x') ylabel('sin(x)') grid on
Output
A 2D line plot showing a smooth blue sine wave from 0 to 2ฯ with labeled axes and grid lines.
Common Pitfalls
Common mistakes when creating plots in MATLAB include:
- Using vectors
xandyof different lengths, which causes errors. - Not labeling axes or adding titles, making the plot hard to understand.
- Overwriting plots without using
hold onwhen plotting multiple lines.
Always check that your data vectors match in size and add labels for clarity.
matlab
x = 1:5; y = [2, 4, 6]; % Different length vectors plot(x, y) % This will cause an error % Correct way: y = [2, 4, 6, 8, 10]; plot(x, y) title('Correct Plot') xlabel('x') ylabel('y')
Output
Error due to vector length mismatch for the first plot; second plot shows a line connecting points (1,2), (2,4), (3,6), (4,8), (5,10) with labels.
Quick Reference
Here is a quick reference for common plot options in MATLAB:
| Option | Description | Example |
|---|---|---|
| '-r' | Red solid line | plot(x, y, '-r') |
| '--g' | Green dashed line | plot(x, y, '--g') |
| ':b' | Blue dotted line | plot(x, y, ':b') |
| 'o' | Circle markers | plot(x, y, 'o') |
| 'LineWidth', 2 | Set line width to 2 | plot(x, y, 'LineWidth', 2) |
| 'MarkerSize', 8 | Set marker size to 8 | plot(x, y, 'o', 'MarkerSize', 8) |
Key Takeaways
Use plot(x, y) with matching vector lengths to create basic 2D plots in MATLAB.
Customize plots with line styles, colors, and markers using the 'LineSpec' argument.
Always label your axes and add titles for clear, understandable plots.
Use hold on to overlay multiple plots without erasing previous ones.
Check vector sizes to avoid errors when plotting.