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

26 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 2 Jun 2018
Edited: MathWorks Support Team on 2 Jun 2018
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:
libname = sprintf('eml_lib/MATLAB Function');
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:
Th following example shows how to programmatically add a MATLAB Function block to a model and populate the block with MATLAB® code-
  1 Comment
Marius on 8 Aug 2014
...long time ago, but I have a problem with the 'Iced'-Property in the Chart. I use the SimEvents-Toolbox. Any ideas?
% new model
mona = 'Test';
% new block 'Attribute Function'
add_block('simeventslib/Attributes/Attribute Function','Test/manipulate_attributes');
% get hanlde for Stateflow.EMChart
sf = sfroot();
sysAF = find_system('simeventslib/Attributes/Attribute Function/MATLAB Function/ SFunction ','LookUnderMasks','all');
AFsFcn = get(cell2mat(get_param(sysAF,'handle')));
HsFcn = sf.find('Path',AFsFcn.Path,'-isa','Stateflow.EMChart');
% I want to place my code here:
I get following error:
>> HsFcn.Script='blabla';
Can't change property while iced
Thanks in advance!

Sign in to comment.

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.


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

Community Treasure Hunt

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

Start Hunting!