Why axes handle deleted in Matlab loop?

Code which tries to mimic the real dynamic condition

clear all; close all; 

hFig2=figure('Units','inches', 'Name', 'Time'); 
hax2=axes(hFig2); 
movegui(hFig2, 'southeast'); 

index=1; 
while (index < 7);
    hFig2=figure(hFig2); 

    u=0:0.01:1+index;
    plot(hax2, u); % Give columns 1xXYZ to Matlab 
    hold on; 
    axis(hax2, 'xy');

    axis(hax2, [0 (size(u,2)/1 - 0) min(u) max(u)]); % to maximise size  
    axis(hax2, 'off'); % no ticks

    index=index+1;
    pause(1); 
    hold off; 
    drawnow    
end;

Logs 1 hax2 in more dynamic condition, Logs 2 hax2 mostly in Code

%% Logs 1 in dynamic condition with failure output
% Failure in more dynamic conditions because axes get deleted for some reason
% hax2
% 
% hax2 = 
% 
%   handle to deleted Axes
% 
%% Logs 2 mostly in Code condition and correct because
% hax2 = 
% 
%   Axes with properties:
% 
%              XLim: [0 201]
%              YLim: [0 2]
%            XScale: 'linear'
%            YScale: 'linear'
%     GridLineStyle: '-'
%          Position: [0.1300 0.1100 0.7750 0.8150]
%             Units: 'normalized'

Error if failure in hax2 i.e. handle to deleted axes for some reason

%% Failure message
%  Show all properties
%
% Warning: MATLAB has disabled some advanced graphics rendering features by switching to software OpenGL. For more information, click
% here. 
% Error using plot
% Invalid handle.
% 
% Error in test_invalid_handle (line 12)
%     plot(hax2, u); 

Some tentative proposals of solutions

  1. Save the axes handle at the end of each loop; possible related thread Save axes handle when plotting In MATLAB
  2. ...

OS: Debian 8.5 64 bit
Matlab: 2016a
Hardware: Asus Zenbook UX303UA
Linux kernel: 4.6 of backports

Upvotes: 0

Views: 1800

Answers (1)

Suever
Suever

Reputation: 65430

When calling axes, the first input should be a parameter/value pair that specifies the parent. If you pass it a single handle graphics input it assumes that input is a handle to an axes

axes(hFig2)

% Error using axes
% Invalid axes handle

Or as you have it written

hax2 = axes(hFig2);

% Error using axes
% Too many output arguments.

Because you are passing an invalid axes handle to it, it doesn't properly assign the handle to a new axes to hax2. It is likely that your deleted hax2 that you're seeing is from a previous run of the script.

Instead, you'll want to use parameter/value pairs to specify the Parent property of the axes.

hax2 = axes('Parent', hFig2);

Also, I would remove the extraneous call to figure every time through the loop since you explicitly specify the parent object of each plot object

Upvotes: 2

Related Questions