如何测试异构数组中元素的class?
How to test the class of elements in a heterogenous array?
MATLAB 支持将属于实现 matlab.mixin.Heterogeneous
的公共根 class 的子class 对象分组到单个数组中,该数组具有最接近的 class共同祖先,例如:
hObj = [ uifigure, uibutton, gobjects(1) ];
K>> class(hObj)
ans =
'matlab.graphics.Graphics'
我想编写一个函数来测试传入的未指定大小的句柄列表(通常是标量,但可能是数组)是否属于特定的硬编码 class 或其后代.
如果输入是标量或同类数组(即所有对象都具有相同的class),并且我们正在测试目标class本身(不包括 subclasses),我们将从这样的函数中得到正确的结果:
function tf = isCorrectClass(hCandidate)
TARGET = 'matlab.ui.Figure';
tf = isa(hCandidate, TARGET);
end
但是,如果hCandidate
是一个异构数组,这将不起作用,所以我们必须这样做:
function tf = isCorrectClass(hCandidate)
TARGET = 'matlab.ui.Figure';
tf = arrayfun(@(x)isa(x, TARGET), hCandidate);
end
之所以有效,是因为从异构数组中选择单个元素会使它们恢复到自己特定的 class。
问题:如何将上面显示的 isCorrectClass
函数调整为以下层次结构,其中目标 class 是 Middle
(假设我的输入数组可能包含任何层次结构的对象 classes)?
% HierarchyRoot "implements" matlab.mixin.Heterogeneous
% / \
% Middle LeafD
% / | \
% LeafA LeafB LeafC
实现此目的的一个简单方法是使用 relational operators of metaclass
对象:
function tf = isCorrectClass(hCandidate)
TARGET = ?Middle; % Assuming such a class exists
tf = arrayfun(@(x)metaclass(x) <= TARGET, hCandidate);
end
其中:
mc = ?ClassName
returns the meta.class
object for the class with name, ClassName
. The ?
operator works only with a class name, not an object.
和metaclass(x) <= TARGET
的意思是x
可以是subclass或与TARGET
相同的class。
MATLAB 支持将属于实现 matlab.mixin.Heterogeneous
的公共根 class 的子class 对象分组到单个数组中,该数组具有最接近的 class共同祖先,例如:
hObj = [ uifigure, uibutton, gobjects(1) ];
K>> class(hObj)
ans =
'matlab.graphics.Graphics'
我想编写一个函数来测试传入的未指定大小的句柄列表(通常是标量,但可能是数组)是否属于特定的硬编码 class 或其后代.
如果输入是标量或同类数组(即所有对象都具有相同的class),并且我们正在测试目标class本身(不包括 subclasses),我们将从这样的函数中得到正确的结果:
function tf = isCorrectClass(hCandidate)
TARGET = 'matlab.ui.Figure';
tf = isa(hCandidate, TARGET);
end
但是,如果hCandidate
是一个异构数组,这将不起作用,所以我们必须这样做:
function tf = isCorrectClass(hCandidate)
TARGET = 'matlab.ui.Figure';
tf = arrayfun(@(x)isa(x, TARGET), hCandidate);
end
之所以有效,是因为从异构数组中选择单个元素会使它们恢复到自己特定的 class。
问题:如何将上面显示的 isCorrectClass
函数调整为以下层次结构,其中目标 class 是 Middle
(假设我的输入数组可能包含任何层次结构的对象 classes)?
% HierarchyRoot "implements" matlab.mixin.Heterogeneous
% / \
% Middle LeafD
% / | \
% LeafA LeafB LeafC
实现此目的的一个简单方法是使用 relational operators of metaclass
对象:
function tf = isCorrectClass(hCandidate)
TARGET = ?Middle; % Assuming such a class exists
tf = arrayfun(@(x)metaclass(x) <= TARGET, hCandidate);
end
其中:
mc = ?ClassName
returns themeta.class
object for the class with name,ClassName
. The?
operator works only with a class name, not an object.
和metaclass(x) <= TARGET
的意思是x
可以是subclass或与TARGET
相同的class。