How do I specify the MATLAB code for the function in an Embedded MATLAB Function Block from the MATLAB command line?

35 views (last 30 days)
I want to use ADD_BLOCK or a similar block construction command to create an Embedded MATLAB Block and specify the MATLAB code inside the block at the same time.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 25 Oct 2023
Edited: MathWorks Support Team on 3 Jan 2024
The ability to specify the MATLAB code for the function in an Embedded MATLAB Function Block requires editing of the Stateflow machine used by the block. Follow these steps:
1. Add a new EML block to the current model (in this case named 'myModel') with the following code:
load_system('eml_lib');
libname = sprintf('eml_lib/MATLAB Function');
add_block(libname,'myModel/myBlockName');
2. Now you can modify the contents with the Stateflow API. First, retrieve a handle to the Stateflow/Simulink Root object:
S = sfroot;
3. Then use the "find" method to find the Stateflow object with the right name in any open models. If the block name is unique, use the following command:
B = S.find('Name','myBlockName','-isa','Stateflow.EMChart');
If the block name is not unique, it is still possible to find the object. Consult the Stateflow API documentation for more information on using the "find" method.
4. Now that you have a handle to the "EMChart", you can modify its properties, including the Script property, where function_script is the contents of your MATLAB file (not including the first FUNCTION line)
B.Script = [function_script];
5. You can then view the contents of the EML block either by double-clicking the block or by typing:
B.view
Th following example shows how to programmatically add a MATLAB Function block to a model and populate the block with MATLAB® code.
Run the below command in your MATLAB instance to access the release specific documentation:
web(fullfile(docroot, 'simulink/ug/add-and-populate-a-matlab-function-block-programmatically.html'))
Please use the below link to search for the required information in the current release: 

More Answers (1)

Muthu Annamalai
Muthu Annamalai on 3 Sep 2014
I have a untested work-around.You can try using a masked block, including this said Stateflow block, and include the property-change code in the 'init' section of the masked block.
It probably has a chance of working.

Categories

Find more on Programmatic Model Editing in Help Center and File Exchange

Products


Release

R14SP1

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!