Specifying Properties of Primary Function Inputs

Why You Must Specify Input Properties

Because C is a statically typed language, Embedded MATLAB MEX must determine the properties of all variables in the M-files at compile time. To infer variable properties in M-files, Embedded MATLAB MEX must be able to identify the properties of the inputs to the primary function, also known as the top-level or entry-point function. Therefore, if your primary function has inputs, you must specify the properties of these inputs, also called preconditions, to Embedded MATLAB MEX. If your primary function has no input parameters, Embedded MATLAB MEX can compile your M-file without modification. You do not need to specify properties of inputs to subfunctions or external functions called by the primary function.

Properties to Specify

If your primary function has inputs, you must specify the following properties for each input:

For:Specify Properties:
ClassSizeComplexitynumerictypefimath
Fixed-point inputs

Structure inputs

 Specify properties for each field according to its class

All other inputs

Default Property Values

Embedded MATLAB MEX assigns the following default values for properties of primary function inputs:

PropertyDefault
classdouble
sizescalar
complexityreal
numerictypeNo default
fimathMATLAB default fimath object

Specifying Default Values for Structure Fields.   In most cases, Embedded MATLAB MEX uses defaults when you don't explicitly specify values for properties — except for structure fields. The only way to name a field in a structure is to set at least one of its properties. Therefore, you may need to specify default values for properties of structure fields. For examples, see Example: Specifying Class and Size of Scalar Structure and Example: Specifying Class and Size of Structure Array.

Specifying Default fimath Values for MEX Functions.   MEX functions generated with Embedded MATLAB MEX use the default fimath value in effect at compile time. You can set the default fimath value explicitly for functions that use fixed-point data by specifying the -F Specify Default fimath option with the emlmex command. If you do not specify a default fimath value on the command line, Embedded MATLAB MEX uses the MATLAB default fimath.

When running MEX functions that depend on the MATLAB default fimath value, do not change this value during your MATLAB session. Otherwise, you receive a runtime error, alerting you to a mismatch between the compile-time and runtime fimath values.

For example, suppose you define the following M-function test:

function y = test %#eml
y = fi(0);

The function test constructs a fi object without explicitly specifying a fimath object. Therefore, test will rely on the default fimath object in effect at compile time. At the MATLAB prompt, generate the MEX function textx to use the factory setting of the MATLAB default fimath:

resetdefaultfimath;
emlmex -o testx test

Next, run testx to display the MATLAB default fimath value:

testx
 
ans =
 
     0

          DataTypeMode: Fixed-point: binary point scaling
                Signed: true
            WordLength: 16
        FractionLength: 15

             RoundMode: nearest
          OverflowMode: saturate
           ProductMode: FullPrecision
  MaxProductWordLength: 128
               SumMode: FullPrecision
      MaxSumWordLength: 128
         CastBeforeSum: true

Now, modify the MATLAB default fimath value so it no longer matches the factory setting used at compile time:

setdefaultfimath(fimath('RoundMode','floor'));

Finally, clear the MEX function from memory and rerun it:

clear testx
testx

The mismatch is detected and causes an error:

??? Error using ==> testx
This function was compiled with a different default fimath 
than the current default.

Supported Classes

The following table presents the class names supported by Embedded MATLAB MEX:

Class NameDescription
logicalLogical array of true and false values
charCharacter array
int88-bit signed integer array
uint88-bit unsigned integer array
int1616-bit signed integer array
uint1616-bit unsigned integer array
int3232-bit signed integer array
uint3232-bit unsigned integer array
singleSingle-precision floating-point or fixed-point number array
doubleDouble-precision floating-point or fixed-point number array
structStructure array
embedded.fiFixed-point number array

Rules for Specifying Properties of Primary Inputs

Follow these rules when specifying the properties of primary inputs:

Methods for Defining Properties of Primary Inputs

You can use any of the following methods to define the properties of primary function inputs:

MethodProsCons

Defining Input Properties by Example at the Command Line

  • Easy to use

  • Does not alter original M-code

  • Designed for prototyping a function that has a small number of primary inputs

  • Must be specified at the command line every time you invoke Embedded MATLAB MEX (unless you use a script)

  • Not efficient for specifying memory-intensive inputs such as large structures and arrays

Defining Input Properties Programmatically in the M-File
  • Integrated with M-code so you do not need to redefine properties each time you invoke Embedded MATLAB MEX

  • Provides documentation of property specifications in the M-code

  • Efficient for specifying memory-intensive inputs such as large structures

  • Uses complex syntax

Defining Input Properties by Example at the Command Line

Command Line Option -eg

The command that invokes Embedded MATLAB MEX — emlmex — provides a command-line option -eg for specifying the properties of primary function inputs as a cell array of example values. The cell array can be a variable or literal array of constant values. Using this option, you specify the properties of inputs at the same time as you compile the M-file with Embedded MATLAB MEX. See -eg Specify Input Properties by Example for emlmex.

Example: Specifying Properties of Primary Inputs by Example.   Consider an M-function that adds its two inputs:

function y = emcf(u,v)
y = u + v;

The following examples show how to specify different properties of the primary inputs u and v by example at the command line:

Example: Specifying Properties of Primary Fixed-Point Inputs by Example.   Consider an M-function that calculates the square root of a fixed-point number:

function y = sqrtfi(x)
y = sqrt(x);

To specify the properties of the primary fixed-point input x by example on the MATLAB command line, follow these steps:

  1. Define the numerictype properties for x, as in this example:

    T = numerictype('WordLength',32,'FractionLength',23,'Signed',true);
  2. Define the fimath properties for x, as in this example:

    F = fimath('SumMode','SpecifyPrecision','SumWordLength',32,
               'SumFractionLength',23,'ProductMode','SpecifyPrecision',
               'ProductWordLength',32,'ProductFractionLength',23);
  3. Create a fixed-point variable with the numerictype and fimath properties you just defined, as in this example:

    myeg = { fi(4.0,T,F) };
  4. Compile the function sqrtfi using the emlmex command, passing the variable myeg as the argument to the-eg option, as in this example:

    emlmex sqrtfi -eg myeg;

Rules for using the -eg option

Follow these rules when using the -eg command-line option to define properties by example:

Specifying Constant Inputs

In cases where you know your primary inputs will not change at runtime, it is more efficient to specify them as constant values than as variables to eliminate unnecessary overhead in generated code. Common uses of constant inputs are for flags that control how an algorithm executes and values that specify the sizes or types of data.

You can define inputs to be constants using the-eg option in one of the following expressions:

ExpressionDescription
-eg { emlcoder.egc(constant_input) }Specifies that an input will be a constant with the size, type, complexity, and value of constant_input
-eg { emlcoder.Example ('const',constant_input ) }Same as emlcoder.egc except that you can construct this expression dynamically using a script and a string variable to represent 'const'

Calling Functions with Constant Inputs.   Embedded MATLAB MEX compiles constant function inputs into the generated code. As a result, the C-MEX function signature differs from the M-function signature. At runtime you supply the constant argument to the M-function, but not to the C-MEX function.

For example, consider the following function identity which copies its input to its output:

%#eml
function y = identity(u)
y = u;

To generate a MEX function identity_mex with a constant input, type the following command at the MATLAB prompt:

emlmex -o identity_mex identity -eg {emlcoder.egc(42)}

To run the M-function, supply the constant argument as follows:

identity(42)

You get the following result:

ans =

    42

Now, try running the C-MEX function with this command:

identity_mex

You should get the same answer.

Example: Specifying a Structure as a Constant Input.   Suppose you define a structure tmp in the MATLAB workspace to specify the dimensions of a matrix, as follows:

tmp = struct('rows', 2, 'cols', 3);

The following M-function rowcol accepts a structure input p to define matrix y:

%#eml
function y = rowcol(u,p)
y = zeros(p.rows,p.cols) + u;

The following examples show two ways to specify that primary input u is a double scalar variable and primary input p is a constant structure:

Defining Input Properties Programmatically in the M-File

Embedded MATLAB MEX lets you use the MATLAB assert function to define properties of primary function inputs directly in your M-file.

How to Use assert with Embedded MATLAB MEX

Use the assert function to invoke standard MATLAB functions for specifying the class, size, and complexity of primary function inputs.

Specify Any Class.  

assert ( isa ( param, 'class_name') )

Sets the input parameter param to the MATLAB class class_name. For example, to set the class of input U to a 32-bit signed integer, call:

...
assert(isa(U,'int32'));
...

Specify fi Class.  

assert ( isfi ( param ) )
assert ( isa ( param, 'embedded.fi' ) )

Sets the input parameter param to the MATLAB class fi (fixed-point numeric object). For example, to set the class of input U to fi, call:

...
assert(isfi(U));
...

or

...
assert(isa(U,'embedded.fi'));
...

Specify Structure Class.  

assert ( isstruct ( param ) )

Sets the input parameter param to the MATLAB class struct (structure). For example, to set the class of input U to a struct, call:

...
assert(isstruct(U));
...

or

...
assert(isa(U,'struct'));
...

Specify Any Size.  

assert ( all ( size (param == [dims ] ) )

Sets the input parameter param to the size specified by dimensions dims. For example, to set the size of input U to a 3-by-2 matrix, call:

...
assert(all(size(U)== [3 2]));
...

Specify Scalar Size.  

assert ( isscalar (param ) )
assert ( all ( size (param == [ 1 ] ) )

Sets the size of input parameter param to scalar. For example, to set the size of input U to scalar, call:

...
assert(isscalar(U));
...

or

...
assert(all(size(U)== [1]));
...

Specify Real Input.  

assert ( isreal (param ) )

Specifies that the input parameter param is real. For example, to specify that input U is real, call:

...
assert(isreal(U));
...

Specify Complex Input.  

assert ( ~isreal (param ) )

Specifies that the input parameter param is complex. For example, to specify that input U is complex, call:

...
assert(~isreal(U));
...

Specify numerictype of Fixed-Point Input.  

assert ( isequal ( numerictype ( fiparam ), T ) )

Sets the numerictype properties of fi input parameter fiparam to the numerictype object T. For example, to specify the numerictype property of fixed-point input U as a signed numerictype object T with 32-bit word length and 30-bit fraction length, use the following code:

...
% Define the numerictype object.
T = numerictype(1, 32, 30);

% Set the numerictype property of input U to T.
assert(isequal(numerictype(U),T));
...

Specify fimath of Fixed-Point Input.  

assert ( isequal ( fimath ( fiparam ), F ) )

Sets the fimath properties of fi input parameter fiparam to the fimath object F. For example, to specify the fimath property of fixed-point input U so that it saturates on integer overflow, use the following code:

...
% Define the fimath object.
F = fimath('OverflowMode','saturate');

% Set the fimath property of input U to F.
assert(isequal(fimath(U),F));
... 

Specify Multiple Properties of Input.  

assert ( function1 ( params ) && function2 ( params ) && function3 ( params ) && ... )

Specifies the class, size, and complexity of one or more inputs using a single assert function call. For example, the following code specifies that input U is a double, complex, 3-by-3 matrix, and input V is a 16-bit unsigned integer:

...
assert(isa(U,'double') && ~isreal(U) && all(size(U) == [3 3]) && isa(V,'uint16'));
... 

Rules for Using assert Function

Follow these rules when using the assert function to specify the properties of primary function inputs:

Example: Specifying General Properties of Primary Inputs

In the following code excerpt, a primary MATLAB function emcspecgram takes two inputs: pennywhistle and win. The code specifies the following properties for these inputs:

InputPropertyValue
pennywhistleclassint16
size220500-by-1 vector
complexityreal (by default)
winclassdouble (by default)
size1024-by-1 vector
complexityreal (by default)

function y = emcspecgram(pennywhistle,win)
nx = 220500;
nfft = 1024;
assert(isa(pennywhistle,'int16'));
assert(all(size(pennywhistle) == [nx 1]));
assert(all(size(win) == [nfft 1]));
...

Alternatively, you can combine property specifications for one or more inputs inside assert commands, as follows:

function y = emcspecgram(pennywhistle,win)
nx = 220500;
nfft = 1024;
assert(isa(pennywhistle,'int16') && all(size(pennywhistle) == [nx 1]));
assert(isa(win, 'double') && all(size(win) == [nfft 1]));
...

Example: Specifying Properties of Primary Fixed-Point Inputs

In the following example, the primary MATLAB function emcsqrtfi takes one fixed-point input: x. The code specifies the following properties for this input:

PropertyValue
classfi
numerictypenumerictype object T, as specified in the primary function
fimathfimath object F, as specified in the primary function
sizescalar (by default)
complexityreal (by default)

function y = emcsqrtfi(x)
T = numerictype('WordLength',32,'FractionLength',23,
                'Signed',true);
F = fimath('SumMode','SpecifyPrecision',
           'SumWordLength',32,'SumFractionLength',23,
           'ProductMode','SpecifyPrecision',
           'ProductWordLength',32,'ProductFractionLength',23);
assert(isfi(x));
assert(isequal(numerictype(x),T));
assert(isequal(fimath(x),F));

y = sqrt(x);

Example: Specifying Class and Size of Scalar Structure

Assume you have defined S as the following scalar MATLAB structure:

S = struct('r',double(1),'i',int8(4));

Here is code that specifies the class and size of S and its fields when passed as an input to your M-function:

function y = fcn(S)

% Specify the class of the input as struct.
assert(isstruct(S));

% Specify the size of the fields r and i
% in the order in which you defined them.
assert(isa(S.r,'double'));
assert(isa(S.i,'int8'));
...

Example: Specifying Class and Size of Structure Array

For structure arrays, you must choose a representative element of the array for specifying the properties of each field. For example, assume you have defined S as the following 2-by-2 array of MATLAB structures:

S = struct('r',{double(1), double(2)},'i',{int8(4), int8(5)});

The following code specifies the class and size of each field of structure input S using the first element of the array:

function y = fcn(S)

% Specify the class of the input S as struct.
assert(isstruct(S));

% Specify the size of the fields r and i
% based on the first element of the array.
assert(all(size(S) == [2 2]));
assert(isa(S(1).r,'double'));
assert(isa(S(1).i,'int8'));

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS