Add and Populate a MATLAB Function Block Programmatically

This example shows how to programmatically add a MATLAB Function block to a model and populate the block with MATLAB® code. If you already have MATLAB code and do not want to add it to a MATLAB Function block manually, this workflow can be convenient.

  1. Create the files for the example.

    • Create and save a model myModel.

    • Create this MATLAB function and save it in myAdd.m.

      function c = myAdd(a, b)
      c = a + b;

  2. Write a MATLAB script that adds a MATLAB Function block to myModel and populates it with the contents of myAdd.m.

    % Add a MATLAB Function block to a model and populate
    % the block with MATLAB code.
    %
    % Copyright 2017 The Mathworks, Inc.
    
    open_system('myModel.slx');
    libraryBlockPath = 'simulink/User-Defined Functions/MATLAB Function';
    newBlockPath = 'myModel/myBlockName';
    add_block(libraryBlockPath, newBlockPath);
    blockHandle = find(slroot, '-isa', 'Stateflow.EMChart', 'Path', newBlockPath);
    blockHandle.Script = fileread('myAdd.m');

    • This line of the script adds a MATLAB Function block to the model:

      add_block(libraryBlockPath, newBlockPath);

    • In memory, open models and their parts are represented by a hierarchy of objects. The root object is slroot. This line of the script returns the object that represents the new MATLAB Function block:

      blockHandle = find(slroot, '-isa', 'Stateflow.EMChart', 'Path', newBlockPath);

    • The Script property of the object contains the contents of the block, represented as a character vector. This line of the script loads the contents of the file myAdd.m into the Script property:

      blockHandle.Script = fileread('myAdd.m');

  3. Run the script.

    You see the new MATLAB Function block in myModel.

  4. To see the code that you added to the block, double-click the block myBlockName.

  5. Save and close the model.

  6. Modify the script for your model.

    • Replace myModel with the name of your model.

    • Set newBlockPath to the path for the new block for your model.

    • Replace myAdd.m with the name of the file that contains the MATLAB function that you want in the MATLAB Function block. Alternatively, you can specify the code directly in a character vector. For example:

      blockHandle.Script = 'function c = fcn(a, b)';

See Also

Related Topics

Was this topic helpful?