how to use hold on in matlab

When working with plots in MATLAB, the "hold on" command allows you to add multiple graphical objects (such as lines, points, or shapes) to the same plot. By default, any new plot command overwrites the existing plot, but with "hold on" enabled, subsequent commands will add to the existing plot.

Here's an example of how to use hold on:

main.m
% Generate some example data
x = 0:0.1:2*pi;
y1 = sin(x); % sine function
y2 = cos(x); % cosine function

% Plot the first function
plot(x, y1);
hold on; % Enable hold mode
% Add the second function to the same plot
plot(x, y2);
% Add some labels and a legend
xlabel('x');
ylabel('y');
title('Trigonometric Functions');
legend('sin', 'cos');
342 chars
16 lines

In this example, the "hold on" command is used to add a second function (cosine) to the same plot as the first function (sine). Without "hold on", the second plot would overwrite the first plot, and only the cosine function would be visible. Instead, both functions are displayed on the same plot, and a legend is added to indicate which is which.

gistlibby LogSnag