MATLAB: Is get(gcf, ‘children’) inconsistent for the same figure handle? Messes up the bode plot when calling the function twice to draw into the same figure.

bodefigureMATLABplot

I have a method that makes a bode plot using bode(sys). It then draws an auxiliary line into the magnitude part of the bode plot by using
childrenHnd = get(gcf, 'children')
magnAxesHnd = childrenHnd(3);
axes(magnAxesHnd);
plot(get(magnAxesHnd, 'XLim'), [0, 0])
which works fine. As you can see, the handle for the magnitude axes is the third element of childrenHnd.
Now I'd like to use the same method to draw another frequency response in the same figure. However, suddenly, when I use the figure handle to get to the magnitude axes handle, it's the second element of childrenHnd. See the following example:
%%plot1
figure(1)
hold on
bode(H1)
childrenHnd = get(gcf, 'children')
magnAxesHnd = childrenHnd(3);
axes(magnAxesHnd);
plot(get(magnAxesHnd, 'XLim'), [0, 0])
hold off
%%plot2
figure(1);
hold on
bode(H2)
childrenHnd = get(gcf, 'children')
magnAxesHnd = childrenHnd(3);
axes(magnAxesHnd);
plot([1 10], [10, 10])
Using this code, my second auxiliary line is drawn in the phase part of the bode plot. Using childrenHnd(2) places the auxiliary line in the intended magnitude part.
Therefore, I can't reuse my method to draw correctly into the same figure. Any good solutions?

Best Answer

To plot the values bode calculates as normal subplot plots, call bode with output arguments:
[mag,phs,wout] = bode(sys);
Magnitude = squeeze(mag);
Phase = squeeze(phs);
figure(1)
subplot(2,1,1)
plot(wout,20*log10(Magnitude(1,:)))
title('Magnitude (dB)')
grid
subplot(2,1,2)
plot(wout,Phase(1,:))
title('Phase (°)')
grid
Related Question