Determine Array Class - MATLAB & Simulink (original) (raw)
Query the Class Name
To determine the class of an array, use the class function:
str = 'Character array'; class(str)
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')
Floating-point values (single and double precision values):
Numeric values (floating-point and integer values):
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')
Using the integer
category also returns true
:
For information on how to distinguish between built-in types and their subclasses, see Test for Subclasses of Built-in Types.
Test for Specific Types
The class function returns the name of the most derived class of an object:
Use the strcmp function with the class
function to check for a specific class of an object:
a = int16(7); strcmp(class(a),'int16')
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')
Test for Subclasses of Built-in Types
The isa
function returns true for subclasses of the specified class. To define functions that require inputs that are MATLABĀ® built-in types but exclude subclasses, use one of these techniques.
Test for Specific Types
Use strcmp
and class
to test for a specific built-in type. This conditional statement checks to see ifinputArg
is single
, and if not, it attempts to convert inputArg
to single
.
if strcmp(class(inputArg),'single') % Call function else inputArg = single(inputArg); end
Test for a Category of Types
Suppose that you create a MEX-function, myMexFcn
, that requires two numeric inputs that must be of type double
orsingle
.
Define a cell array that contains the character arraysdouble
and single
:
floatTypes = {'double','single'};
Use strcmp
and class
to test the inputs against the types specified in the cell array.
if any(strcmp(class(a),floatTypes)) && ... any(strcmp(class(b),floatTypes)) outArray = myMexFcn(a,b); else % Try to convert inputs to avoid error ... end
Use isobject
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)
This conditional tests if arr
is an array is one of the built-in integer types.
if isa(arr,'integer') && ~isobject(arr) % if previous statement is true, arr is a built-in integer type ... end