Main Content

このページの内容は最新ではありません。最新版の英語を参照するには、ここをクリックします。

配列クラスの判定

クラス名のクエリ

配列のクラスを判定するには、関数 class を使用します。

a = [2,5,7,11];
class(a)
ans =
double
str = 'Character array';
class(str)
ans =
char

配列クラスのテスト

関数 isa を使用して、特定のクラスや数値クラスのカテゴリ (numericfloatinteger) をテストできます。

a = [2,5,7,11];
isa(a,'double')
ans =
     1

浮動小数点値 (単精度および倍精度の値):

isa(a,'float')
ans =
     1

数値 (浮動小数点値および整数値):

isa(a,'numeric')
ans =
     1

isa はサブクラスに 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 =
     1

integer カテゴリを使用した場合も 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

最派生クラスのテスト

以下の入力を必要とする関数を定義する場合、

  • MATLAB® 組み込み型

  • MATLAB 組み込み型のサブクラス以外

次の手法を使用して入力引数から組み込み型のサブクラスを除外します。

  • 関数で受け入れることができる組み込み型の名前を含んだ cell 配列を定義します。

  • class および strcmp を呼び出して、MATLAB コントロール ステートメント内の特定の型をテストします。

入力引数をテストします。

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'};
% Test for proper types
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 は組み込み型のインスタンスに対して false を返します。

% Create a int16 array
a = int16([2,5,7,11]);
isobject(a)
ans =
     0

配列が組み込み整数型のいずれかであるか判断します。

if isa(a,'integer') && ~isobject(a)
   % a is a built-in integer type
   ...
end