20.11 M文件例子
精通MATLAB工具箱含有许多实用函数,它们可以验证本章的许多概念。这些函数的基本部分已经在二维和三维图形这些章阐述过了。有了前面对句柄图形的讨论,我们现在可以更彻底地讨论这些函数。
最简单的精通MATLAB工具箱的函数之一提出了一个共同的问题。MATLAB函数gcf返回当前图形的句柄。但是,它有一个副作用。如果图形不存在,gcf就创建一个,并返回它的句柄。如果想寻找一个图形是否存在于头一个位置,要是没有,又不得不创建,怎么办?函数mmgcf正好实现由其内容所描述的工作。
function HF=mmgcf
%MMGCF Get Current Figure if it Exists.
% MMGCF returns the handle of the current figure if it exists.
% If no current figure exists,MMGCF returns an empty handle.
%
% Note that the function GCF is different.It creates a figure and returns its handle if it does not % exist.
% Copyright (c) 1996 by Prentice-Hall,Inc.
Hf=get(0, ‘Children’ ); % check for figure children
if isempty(Hf)
return
else
Hf=get(0, ‘CurrentFigure’ );
end
函数mmgcf首先检查根对象的子对象的图形是否存在,如至少有一个图形对象时,根对象的 ‘CurrentFigure’ 属性就返回当前的图形。
函数mmgca为坐标轴对象执行同样的功能,如同在它的M文件内所描述的那样。
function Ha=mmgca
%MMGCA Get Current Axes if it exists.
% MMGCA returns the handle of the current axes if it exists.
% If no current axes exists,MMGCA returns an empty handle.
%
% Note that the function GCA is diffent.It create a figure and an axes and returns the axes % handle if they do not exist.
% Copyright (c) 1996 by Prentice-Hall,Inc.
Ha=findobj(0, ‘Type’ , ‘axes’ );
if isempty(Ha)
return
else
Ha=get(get(0, ‘CurrentFigfure’ ), ‘CurrentAxes’ );
end
由于函数gco已经表现出当对象不存在时返回空矩阵的行为特性,就不需要函数mmgco了。
在精通MATLAB工具箱中的另一个函数是mmzap,在二维图形那一章里已作过介绍。如下M文件中所示,它使用mmgcf作错误检查,与findobj和get一起删除一个指定的图形。
function mmzap(arg)
%MMZAP Delete graphics object using mouse.
% MMZAP waits for a mouse click on an object in a figure window and deletes the object.
% MMZAP or MMZAP text erases text objects.
% MMZAP axes erases axes objects.
% MMZAP line erases line objects.
% MMZAP surf erases surface objects.
% MMZAP patch erases patch objects.
%
% Clicking on an object other than the selected type or striking a key on the keyboard aborts % the command.
% Copyright (c) 1996 by Prentice-Hall,Inc.
if nargin<1,arg= ‘text’ ;end
H