配列クラスの判定
クラス名のクエリ
配列のクラスを判定するには、関数 class を使用します。
a = [2,5,7,11]; class(a)
ans = double
str = 'Character array';
class(str)ans = char
配列クラスのテスト
関数 isa を使用して、特定のクラスや数値クラスのカテゴリ (numeric、float、integer) をテストできます。
a = [2,5,7,11];
isa(a,'double')
ans =
1浮動小数点値 (単精度および倍精度の値):
isa(a,'float')
ans =
1数値 (浮動小数点値および整数値):
isa(a,'numeric')
ans =
1isa はサブクラスに true を返す
isa は指定されたクラスから派生したクラスに対して true を返します。たとえば、SubInt クラスは int16 組み込み型から派生します。
classdef SubInt < int16 methods function obj = SubInt(data) if nargin == 0 data = 0; end obj = obj@int16(data); end end end
定義により、SubInt クラスのインスタンスは int16 クラスのインスタンスでもあります。
aInt = SubInt;
isa(aInt,'int16')
ans =
1integer カテゴリを使用した場合も true が返されます。
isa(aInt,'integer')
ans =
1組み込み型とそのサブクラスを区別する方法の詳細については、組み込み型のサブクラスのテストを参照してください。
特定の型のテスト
関数 class はオブジェクトの "最派生" クラスの名前を返します。
class(aInt)
ans = SubInt
関数 strcmp を関数 class と共に使用して、オブジェクトの特定のクラスをチェックします。
a = int16(7);
strcmp(class(a),'int16')
ans =
1関数 class はクラス名を char ベクトルで返すため、strcmp により実行された比較の結果は継承の影響を受けません。
aInt = SubInt;
strcmp(class(aInt),'int16')
ans =
0組み込み型のサブクラスのテスト
関数 isa は指定されたクラスのサブクラスに対して true を返します。MATLAB® 組み込み型でサブクラス以外の入力を必要とする関数を定義するには、以下の手法のいずれかを使用します。
特定の型のテスト
特定の組み込み型をテストするには、strcmp と class を使用します。次の条件文は、inputArg が single であるかどうかを確認し、そうでない場合は inputArg を single に変換するよう試みます。
if strcmp(class(inputArg),'single') % Call function else inputArg = single(inputArg); end
型のカテゴリのテスト
double 型または single 型の 2 つの数値入力を必要とする MEX 関数 myMexFcn を作成するとします。
outArray = myMexFcn(a,b)
文字配列 double および single を含む cell 配列を定義します。
floatTypes = {'double','single'};strcmp と class を使用して、入力が cell 配列で指定された型であるかどうかをテストします。
if any(strcmp(class(a),floatTypes)) && ... any(strcmp(class(b),floatTypes)) outArray = myMexFcn(a,b); else % Try to convert inputs to avoid error ... end
isobject の使用
isobject を使用して、組み込み型を組み込み型のサブクラスと区別します。関数 isobject は、組み込み型のインスタンスに対して false を返します。
% Create a int16 array
a = int16([2,5,7,11]);
isobject(a)
ans =
0次の条件文は、arr がいずれかの組み込み整数型の配列であるかどうかをテストします。
if isa(arr,'integer') && ~isobject(arr) % if previous statement is true, arr is a built-in integer type ... end