Skip to Main Content Skip to Search
Product Documentation

MATLAB Function Block

Composing a MATLAB Language Function in a Simulink Model

The MATLAB Function block lets you compose a MATLAB language function in a Simulink model that generates embeddable code. When you simulate the model or generate code for a target environment, a function in a MATLAB Function block generates efficient C/C++ code. This code meets the strict memory and data type requirements of embedded target environments. In this way, the MATLAB Function blocks bring the power of MATLAB for the embedded environment into Simulink.

For more information about the MATLAB Function block and code generation, refer to the followingn:

Using the MATLAB Function Block with Data Type Override

When you use the MATLAB Function block in a Simulink model that specifies data type override, the block determines the data type override equivalents of the input signal and parameter types. The block then uses these equivalent values to run the simulation. The following table shows how the MATLAB Function block determines the data type override equivalent using

Input Signal or Parameter TypeData Type Override SettingData Type Override Equivalent
Inherited singleDoublefi double
Singlefi single
Specified singleDoubleBuilt-in double
SingleBuilt-in single
Inherited doubleDoublefi double
Singlefi single
Specified doubleDoubleBuilt-in double
SingleBuilt-in single
Inherited FixedDoublefi double
Singlefi single
Specified FixedDoublefi double
Singlefi single

For more information about using the MATLAB Function block with data type override, see the following section of the Simulink documentation:

Using Data Type Override with the MATLAB Function Block

Using Fixed-Point Data Types with the MATLAB Function Block

Code generation from MATLAB supports a significant number of Fixed-Point Toolbox functions. Refer to Functions Supported for Code Acceleration and Code Generation from MATLAB for information about which Fixed-Point Toolbox functions are supported.

For more information on working with fixed-point MATLAB Function blocks, see:

Specifying Fixed-Point Parameters in the Model Explorer

You can specify parameters for an MATLAB Function block in a fixed-point model using the Model Explorer. Try the following exercise:

  1. Place a MATLAB Function block in a new model. You can find the block in the Simulink User-Defined Functions library.

  2. Open the Model Explorer by selecting View > Model Explorer from your model.

  3. Expand the untitled* node in the Model Hierarchy pane of the Model Explorer. Then, select the MATLAB Function node. The Model Explorer now appears as shown in the following figure.

The following parameters in the Dialog pane apply to MATLAB Function blocks in models that use fixed-point and integer data types:

Treat these inherited Simulink signal types as fi objects

Choose whether to treat inherited fixed-point and integer signals as fi objects.

  • When you select Fixed-point, the MATLAB Function block treats all fixed-point inputs as Fixed-Point Toolbox fi objects.

  • When you select Fixed-Point & Integer, the MATLAB Function block treats all fixed-point and integer inputs as Fixed-Point Toolbox fi objects.

MATLAB Function block fimath

Specify the fimath properties for the block to associate with the following objects:

  • All fixed-point and integer input signals to the MATLAB Function block that you choose to treat as fi objects.

  • All fi and fimath objects constructed in the MATLAB Function block.

You can select one of the following options for the MATLAB Function block fimath:

  • Same as MATLAB — When you select this option, the block uses the same fimath properties as the current default fimath. The edit box appears dimmed and displays the current default fimath in read-only form.

  • Specify other — When you select this option, you can specify your own fimath object in the edit box.

For more information on these parameters, see Using fimath Objects in MATLAB Function Blocks.

Using fimath Objects in MATLAB Function Blocks

The MATLAB Function block fimath parameter enables you to specify one set of fimath object properties for the MATLAB Function block. The block associates the fimath properties you specify with the following objects:

You can set these parameters on the following dialog box, which you can access through either the Model Explorer or the Ports and Data Manager.

When you select Same as MATLAB for the MATLAB Function block fimath, the MATLAB Function block uses the current default fimath. The current default fimath appears dimmed and in read-only form in the edit box.

When you select Specify other the block allows you to specify your own fimath object in the edit box. You can do so in one of two ways:

The Fixed-Point Toolbox isfimathlocal function supports code generation for MATLAB.

Sharing Models with Fixed-Point MATLAB Function Blocks

When you collaborate with a coworker, you can share a fixed-point model using the MATLAB Function block. To share a model, make sure that you move any variables you define in the MATLAB workspace, including fimath objects, to the model workspace. For example, try the following:

  1. Place a MATLAB Function block in a new model. You can find the block in the Simulink User-Defined Functions library.

  2. Define a fimath object in the MATLAB workspace that you want to use for any Simulink fixed-point signal entering the MATLAB Function block as an input:

    F = fimath('RoundMode','Floor','OverflowMode','Wrap',...
        'ProductMode','KeepLSB','ProductWordLength',32,...
        'SumMode','KeepLSB','SumWordLength',32)
     
    F =
                  RoundMode: floor
              OverflowMode: wrap
               ProductMode: KeepLSB
         ProductWordLength: 32
                   SumMode: KeepLSB
             SumWordLength: 32
             CastBeforeSum: true
  3. Open the Model Explorer by selecting View > Model Explorer from your model.

  4. Expand the untitled* node in the Model Hierarchy pane of the Model Explorer, and select the MATLAB Function node.

  5. Select Specify other for the MATLAB Function block fimath parameter and enter the variable F into the edit box on the Dialog pane. Click Apply to save your changes.

    You have now defined the fimath properties to be associated with all Simulink fixed-point input signals and all fi and fimath objects constructed within the block.

  6. Select the Base Workspace node in the Model Hierarchy pane. You can see the variable F that you have defined in the MATLAB workspace listed in the Contents pane. If you send this model to a coworker, that coworker must first define that same variable in the MATLAB workspace to get the same results.

  7. Cut the variable F from the base workspace, and paste it into the model workspace listed under the node for your model, in this case, untitled*. The Model Explorer now appears as shown in the following figure.

    You can now email your model to a coworker. Because you included the required variables in the workspace of the model itself, your coworker can simply run the model and get the correct results. Receiving and running the model does not require any extra steps.

Example: Implementing a Fixed-Point Direct Form FIR Using the MATLAB Function Block

The following sections lead you through creating a fixed-point, low-pass, direct form FIR filter in Simulink. To create the FIR filter, you use Fixed-Point Toolbox software and the MATLAB Function block. In this example, you perform the following tasks in the sequence shown:

Program the MATLAB Function Block

  1. Place a MATLAB Function block in a new model. You can find the block in the Simulink User-Defined Functions library.

  2. Save your model as cgen_fi.mdl.

  3. Double-click the MATLAB Function block in your model to open the MATLAB Function Block Editor. Type or copy and paste the following MATLAB code, including comments, into the Editor:

    function [yout,zf] = dffirdemo(b, x, zi)
    %codegen_fi doc model example
    %Initialize the output signal yout and the final conditions zf
    Ty = numerictype(1,12,8);
    yout = fi(zeros(size(x)),'numerictype',Ty);
    zf = zi;
    
    % FIR filter code
    for k=1:length(x);
      % Update the states: z = [x(k);z(1:end-1)]  
      zf(:) = [x(k);zf(1:end-1)];
      % Form the output: y(k) = b*z
      yout(k) = b*zf;
    end
    
    % Plot the outputs only in simulation.
    % This does not generate C code.
    coder.extrinsic('figure');
    coder.extrinsic('subplot');
    coder.extrinsic('plot');
    coder.extrinsic('title');
    coder.extrinsic('grid');
    figure;
    subplot(211);plot(x); title('Noisy Signal');grid;
    subplot(212);plot(yout); title('Filtered Signal');grid;

Prepare the Inputs

Define the filter coefficients b, noise x, and initial conditions zi by typing the following code at the MATLAB command line:

b=fidemo.fi_fir_coefficients;
load mtlb
x = mtlb;
n = length(x);
noise = sin(2*pi*2140*(0:n-1)'./Fs);
x = x + noise;
zi = zeros(length(b),1);

Create the Model

  1. Add blocks to your model to create the following system.

  2. Set the block parameters in the model to the following values.

    BlockParameterValue
    ConstantConstant valueb
    Interpret vector parameters as 1-DUnselected
    Sampling modeSample based
    Sample timeinf
    ModeFixed point
    SignednessSigned
    ScalingSlope and bias
    Word length12
    Slope2^-12
    Bias0
    Constant1Constant valuex+noise
    Interpret vector parameters as 1-DUnselected
    Sampling modeSample based
    Sample time1
    ModeFixed point
    SignednessSigned
    ScalingSlope and bias
    Word length12
    Slope2^-8
    Bias0
    Constant2Constant valuezi
    Interpret vector parameters as 1-DUnselected
    Sampling modeSample based
    Sample timeinf
    ModeFixed point
    SignednessSigned
    ScalingSlope and bias
    Word length12
    Slope2^-8
    Bias0

    To Workspace
    Variable nameyout
    Limit data points to lastinf
    Decimation1
    Sample time-1
    Save formatArray
    Log fixed-point data as a fi objectSelected
    To Workspace1Variable namezf
    Limit data points to lastinf
    Decimation1
    Sample time-1
    Save formatArray
    Log fixed-point data as a fi objectSelected
    To Workspace2Variable namenoisyx
    Limit data points to lastinf
    Decimation1
    Sample time-1
    Save formatArray
    Log fixed-point data as a fi objectSelected

  3. From the model menu, select Simulation > Configuration Parameters and set the following parameters.

    ParameterValue
    Stop time0
    TypeFixed-step
    Solverdiscrete (no continuous states)

    Click Apply to save your changes.

Define the fimath Object Using the Model Explorer

  1. Open the Model Explorer for the model.

  2. Click the cgen_fi > MATLAB Function node in the Model Hierarchy pane. The dialog box for the MATLAB Function block appears in the Dialog pane of the Model Explorer.

  3. Select Specify other for the MATLAB Function block fimath parameter on the MATLAB Function block dialog box. You can then create the following fimath object in the edit box:

    fimath('RoundMode','Floor','OverflowMode','Wrap',...
        'ProductMode','KeepLSB','ProductWordLength',32,...
        'SumMode','KeepLSB','SumWordLength',32)
    

    The fimath object you define here is associated with fixed-point inputs to the MATLAB Function block as well as the fi object you construct within the block.

    By selecting Specify other for the MATLAB Function block fimath, you ensure that your model always uses the fimath properties you specified.

Run the Simulation

  1. Run the simulation by selecting your model and typing Ctrl+T. While the simulation is running, information outputs to the MATLAB command line. You can look at the plots of the noisy signal and the filtered signal.

  2. Next, build embeddable C code for your model by selecting the model and typing Ctrl+B. While the code is building, information outputs to the MATLAB command line. A folder called coder_fi_grt_rtw is created in your current working folder.

  3. Navigate to coder_fi_grt_rtw > coder_fi.c. In this file, you can see the code generated from your model. Search for the following comment in your code:

    /* coder_fi doc model example */

    This search brings you to the beginning of the section of the code that your MATLAB Function block generated.

  


Free Early Verification Kit

Learn how to apply early verification to your development process through these technical resources.

How much time do you spend on testing to ensure implementation meets system-level requirements?

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