Main Content

Testing 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 technique 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.

The following code tests an input argument, inputArg:

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

Testing for a 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 floatTypes that contains the words 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

You can use isobject to separate built-in types from subclasses of built-in types. The isobject function returns false for instances of built-in types. For example:

% 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