How to check if an object is from a certain class object?

129 ビュー (過去 30 日間)
Limanan Nursalim
Limanan Nursalim 2018 年 4 月 24 日
コメント済み: Steven Lord 2020 年 6 月 25 日
I want to check if an item is actually a box, so here is a box:
classdef Box
properties
u
v
n
end
methods
%%constructor
function obj = Box(u,v)
if nargin == 0
error('insert parameters u and v');
end
if nargin == 2 && isvector(u) && isvector(v)
if length(u) ~= length(v)
error('length of u unequals length of v')
end
for i = 1:length(u)
if u(i) == v(i)
error('%s th component of input are the same', i)
end
end
obj.u = u;
obj.v = v;
obj.n = length(u);
return;
end
end
end
end
and then I used
u = zeros(3,1); v = ones(3,1); a = Box(u,v)
isa(a,Box)
but isa(object,Classobject) is somehow function calling constructor of the class object, and returns the error from which nargin == 0. How do I properly check if object a is a box?
  2 件のコメント
per isakson
per isakson 2018 年 4 月 24 日
>> isa( a, 'Box' )
ans =
     1
Al in St. Louis
Al in St. Louis 2020 年 6 月 25 日
This bites me each time I go to use it! (I only use it once every two to three years.)

サインインしてコメントする。

回答 (1 件)

Sayyed Ahmad
Sayyed Ahmad 2020 年 6 月 25 日
try this:
isequal(class(a),'Box')
ans =
1
  1 件のコメント
Steven Lord
Steven Lord 2020 年 6 月 25 日
That would work in this particular example, but it wouldn't work with subclasses. Let's take two classes:
classdef Animal
% Some general methods and properties: Move, numberOfLegs, etc.
end
and
classdef Dog < Animal
% Some specific methods and properties: Bark, breed (property), etc.
% This also inherits Move and numberOfLegs from Animal
end
If we create a Dog object, is it an Animal?
D = Dog();
isa(D, 'Animal') % true
isequal(class(D), 'Animal') % false

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by