MATLAB: Hold on – best practice question

best practicehold onMATLABplots hold onwhere to use hold on

I wonder if there is any real difference between two following versions of 'hold on' application:
  • Case 1 – 'hold on' is used directly after the 'figure' declaration
  • Case 2 – 'hold on' is used after the first plot
% DATA
x = 1:10;
y1 = x.^2;
y2 = x.^3;
% PLOTS
% Case 1 - 'hold on' after 'figure' declaration
figure
hold on;
plot(x, y1);
plot(x, y2);
% Case 2 - 'hold on' after 1st plot
figure
plot(x, y1);
hold on;
plot(x, y2);
  • Is there any performance gain/loss between these two cases?
  • Or it is entirely down to the preference of the person writing the code?
I'm asking as I noticed that many people use 'Case 1' style, which I personally find more elegant. but on the other hand, all the examples featured in the Matlab documentation use the 'Case 2' style.
To add a bit more into the mix, I came across this thread, where Jan Simon abstains from using 'hold on' function altogether in favour of using handles:
So, what is the 'best practice' in this regard?

Best Answer

Especially inside loops I do not like to call hold('on') repeatedly. Therefore I avoid this command in general, but set the property of the axes manually:
AxesH = axes('NextPlot', 'add');
This is what happens inside hold also. I admit that this looks a little bit "low level" and hold('on') might look easier. But this has the addition advantage, that a plot command does not skip formerly defined axes properties like limits or tickmarks.
And as code: Compare:
for k = 1:10
plot(1:10, rand(1, 10));
hold('on');
end
with:
AxesH = axes('NextPlot', 'add');
for k = 1:10
plot(AxesH, 1:10, rand(1, 10));
end