Monday, November 11, 2013

Hold On!

There's a weird bug in MATLAB with the function HOLD ON. I'm sure we've all used HOLD ON when making figure — it needs to be used in order to plot multiple lines. However, WHERE the HOLD ON command is used makes a big different in the appearance of plots.

For instance, if I were to write the commands:

% define some function
x = 0:0.1:2*pi;
y1 = sin(x);
y2 = cos(x);

% plot the functions
figure

% subplot 1: plot the first function BEFORE using HOLD ON
subplot(211)
plot(x,y1,'linewidth',2)
hold on
plot(x,y2,'r','linewidth',2)

% subplot 2: plot the first function AFTER using HOLD ON
subplot(212)
hold on
plot(x,y1,'linewidth',2)
plot(x,y2,'r','linewidth',2)


The following figure results:




There is a border around the plot on all four sides in the top subplot, whereas there is only a border on the bottom and left in the bottom subplot. This difference is due ONLY to the position of the HOLD ON command. 

When HOLD ON comes AFTER the first function is plotted, an entire border is plotted. Whereas, when HOLD ON comes BEFORE the first function is plotted, the border is only on the left and bottom.


The position of HOLD ON not only changes the plot borders, but it can change how the data is plotted, such as with SEMILOGY:

% define a random function that will vary over a large range
x = 1:100;
y = 2.^(rand(100,1)*100);

figure

% plot SEMILOGY before HOLD ON is used
subplot(211)
semilogy(x,y,'linewidth',2)
hold on

% plot SEMILOGY after HOLD ON is used
subplot(212)
hold on
semilogy(x,y,'linewidth',2)

The following figure results:




In this case, not only is there the same difference with the subplot borders, but when HOLD ON is used BEFORE SEMILOGY, MATLAB just uses a regular plot command rather than SEMILOGY as seen in the second subplot. HOLD ON must not be used before SEMILOGY for SEMILOGY to plot correctly. 


I was confused by this bug for quite a while, not understanding why sometimes I would get an entire border around my figures and sometimes I wouldn't. Once I figured out that it was the placement of the HOLD ON command that changed the border, I actually started strategically placing HOLD ON to avoid having to use the BOX ON and BOX OFF commands to turn the top and right borders on and off. 

It was today that I realized that the placement of HOLD ON also is what prevents SEMILOGY from working correctly! Knowing this bug will prevent many headaches in the future.

1 comment:

  1. That's helpful - I never realized why the box disappeared sometimes..

    ReplyDelete