Check if handle to axes exists at all [R2017b]

5 次查看(过去 30 天)
Hi,
I am trying to check if an axes handle exists and if not create it, e.g.:
X = [1:100];
Y=sin(X);
if handle exists
a=line(h, X, Y);
else
f=figure();
h=axes(figure);
end
In the case where it hasn't been created I keep getting an error 'Undefined function or variable' when I use ishandle or any get statement.

采纳的回答

Jan
Jan 2018-1-17
编辑:Jan 2018-1-17
The code is not meaningful. You can always know, if the axes has been created before or not. Therefore it is not clear, what you are exactly asking for. Maybe this helps:
f = gobjects(0);
h = gobjects(0);
% Then a magic section, which does not let you know if the axes is
% existing or not:
if rand > 0.5
f = figure;
h = axes; %
end
...
if ~isgraphics(h) % Better than ishandle
f = figure;
h = axes; %
end
line(x, 1:10, rand(1, 10))
So define the variable holding the handle as an empty graphics object at first. The empty matrix would work also. Then you can check if the variable contains a valid graphics object.
  5 个评论
Jan
Jan 2018-1-17
In both scenarios using the method I've suggested works well. Example:
FigH = figure;
axes;
LineH = gobjects(0);
for k = 1:1000
if isgraphics(h) % of ishghandle(h)
if isgraphics(LineH)
LineH = plot(1:10, rand(1, 10));
else
set(LineH, 'YData', rand(1, 10));
pause(1);
end
else
disp('User has closed the figure');
break;
end
end
Here isgraphics is used to check, if the figure is still existing and if the line object has been created before, to allow a cheaper setting of YData instead of a re-creation.
Does this help?
TJ
TJ 2018-1-18
Hi Jan,
Using this I managed to achieve my goal. Thank you.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Graphics Object Programming 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by