0
0
MatlabHow-ToBeginner ยท 3 min read

How to Hold Plot in MATLAB: Use hold on and hold off

In MATLAB, use hold on to keep the current plot and add new plots on top of it. Use hold off to release the plot hold and allow new plots to replace the existing one.
๐Ÿ“

Syntax

The basic commands to control plot holding in MATLAB are:

  • hold on: Keeps the current plot so new plots add to it.
  • hold off: Releases the hold so new plots replace the current plot.
  • hold: Toggles the hold state (on/off).
matlab
hold on
hold off
hold
๐Ÿ’ป

Example

This example shows how to plot two lines on the same figure by using hold on. The first plot is a sine wave, and the second is a cosine wave added on top.

matlab
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y, 'b-', 'LineWidth', 2); % Plot sine wave
hold on; % Hold the plot
z = cos(x);
plot(x, z, 'r--', 'LineWidth', 2); % Add cosine wave
hold off; % Release the hold
legend('sin(x)', 'cos(x)');
title('Plot with hold on and hold off');
xlabel('x');
ylabel('y');
Output
A figure window opens showing a blue solid sine wave and a red dashed cosine wave plotted together on the same axes.
โš ๏ธ

Common Pitfalls

Common mistakes when using hold include:

  • Forgetting to use hold on before plotting multiple graphs, which causes the new plot to replace the old one.
  • Not using hold off after finishing, which can cause unexpected plots to overlay later.
  • Using hold without arguments can toggle the state unintentionally.
matlab
x = 0:0.1:2*pi;
plot(x, sin(x)); % First plot
plot(x, cos(x)); % This replaces the first plot

% Correct way:
plot(x, sin(x));
hold on;
plot(x, cos(x));
hold off;
Output
First two plot commands show only the cosine wave because it replaces the sine wave. The correct way shows both sine and cosine waves on the same figure.
๐Ÿ“Š

Quick Reference

CommandDescription
hold onKeep current plot and add new plots on top
hold offRelease hold so new plots replace current plot
holdToggle hold state (on/off)
โœ…

Key Takeaways

Use hold on to add multiple plots to the same figure without erasing.
Use hold off to stop adding plots and allow new plots to replace the old.
Always call hold on before plotting multiple datasets on one figure.
Remember to release the hold with hold off to avoid unexpected overlays.
The hold command without arguments toggles the hold state, which can be confusing.