MATLAB: Putting “hold on” or “hold off” before every plot.

plots

Is it good practice to put "hold on" or "hold off" before every plot? Or does it not matter?

Best Answer

It is not usually good practice to put "hold on" before the first plot, but sometimes it is needed.
Once there is an existing plot, if you distinctly put "hold on" before or after every plot call, it can make it seem like you don't understand how "hold on" works.
A lot of "good practice" involves writing to other people's expectations. When you do something unusual then even if it is correct you can confuse readers about why you did it, whether it means something different than what they are accustomed to.
One typical practice that everyone understands is to have "hold on" in a loop, like
for K = 1 : 5
plot(rand(1,20));
hold on
end
Even though the hold is "on" after the first time, people have seen this so often that they do not need to see
for K = 1 : 5
plot(rand(1,20));
if K == 1; hold on; end
end
to understand that the "hold on" is not really needed for the remaining loop iterations. This kind of special test so that the hold is only done once can confuse people who are not accustomed to thinking about the meaning of "hold on". It can be worth putting in the test, though, for efficiency reasons: the extra overhead of the "if" every time is less than the overhead of the extra call to "hold" each time. If your loop has a lot of iterations, the time savings of the test can be worth it (provided that you build it in right when you write the loop -- remember, it takes lot of extra execution time to balance the cost of a human analyzing the efficiency at this level.)
I do not think I would ever prefix a plot call with "hold off". If I wanted to get rid of everything that was in the axes, because whatever is in the axes has no relationship to what I am about to plot, then I would cla(). If it was in a loop that was updating the content of the axes, then it would almost always be more efficient to record the plot handles of the objects that are going to need to be updated, and then to have the loop itertions other than the first one set() the properties of the handles to the new data. For example, instead of
for K = 1 : 20
hold off
plot(rand(1,20));
title(sprintf('iteration #%d', K));
drawnow();
end
you would use
ph = plot(rand(1,20));
th = title('iteration #1');
drawnow();
for K = 2 : 20
set(ph, 'YData', rand(1,20));
set(th, 'String', sprintf('iteration #%d', K));
drawnow();
end