Documentation

Determine Array Class

Query the Class Name

To determine the class of an array, use the class function:

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

Test for Array Class

The isa function enables you to test for a specific class or a category of numeric class (numeric, float, integer):

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

Floating-point values (single and double precision values):

isa(a,'float')
ans =
1

Numeric values (floating-point and integer values):

isa(a,'numeric')
ans =
1

isa Returns True for Subclasses

isa returns true for classes derived from the specified class. For example, the SubInt class derives from the built-in type int16:

classdef SubInt < int16
methods
function obj = SubInt(data)
if nargin == 0
data = 0;
end
obj = obj@int16(data);
end
end
end

By definition, an instance of the SubInt class is also an instance of the int16 class:

aInt = SubInt;
isa(aInt,'int16')
ans =
1

Using the integer category also returns true:

isa(aInt,'integer')
ans =
1

Test for Specific Types

The class function returns the name of the most derived class of an object:

class(aInt)
ans =
SubInt

Use the strcmp function with the class function to check for a specific class of an object:

a = int16(7);
strcmp(class(a),'int16')
ans =
1

Because the class function returns the class name as a char vector, the inheritance does not affect the result of the comparison performed by strcmp:

aInt = SubInt;
strcmp(class(aInt),'int16')
ans =
0

Test for Most Derived Class

If you define functions that require inputs that are:

• MATLAB® built-in types

• Not subclasses of MATLAB built-in types

Use the following techniques to exclude subclasses of built-in types from the input arguments.

• Define a cell array that contains the names of built-in types accepted by your function.

• Call class and strcmp to test for specific types in a MATLAB control statement.

Test an input argument:

if strcmp(class(inputArg),'single')
% Call function
else
inputArg = single(inputArg);
end

Test for Category of Types

Suppose that you create a MEX-function, myMexFcn, that requires two numeric inputs that must be of type double or single:

outArray = myMexFcn(a,b)

Define a cell array that contains the character arrays double and single:

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

Another Test for Built-In Types

Use isobject to separate built-in types from subclasses of built-in types. The isobject function returns false for instances of built-in types:

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

Determine if an array is one of the built-in integer types:

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