4

I'd like to create a simple Simulink model containing a "MATLAB Function" block programmatically -- i.e. using Matlab code.

Thanks to this guide, I've managed to create a new model containing the block:

open_system(new_system('my_system'))
add_block('simulink/User-Defined Functions/MATLAB Function', 'my_system/my_func')

Usually, in order to edit the "MATLAB Function" block's code, one has to "open" the block by double-clicking on it then entering the new code.

However, I would like to set that code programmatically using e.g. set_param() or any relevant function.

For instance, to set the following as the block's code:

function y = fcn(v)
%#codegen

y = 2 * u;

I would like to use something like:

set_param('my_system/my_func', 'Script',...
    'function y = fcn(u)\n%#codegen\n\ny = 2 * u;'...
);

I've looked at the output of get_param('my_system/my_func', 'ObjectParameters') and tried to guess which parameter might be used to set the block's function code: So far, I couldn't find any. Therefore, my question is:

Q: Is it possible, using only Matlab commands, to set the code of a "MATLAB Function" block in Simulink?

2
  • 1
    This is an interesting question. Instead of editing the question, post an answer with whatever helped you. Commented Feb 16, 2017 at 10:11
  • @Ander Biguri: Done ;) Commented Feb 16, 2017 at 10:55

1 Answer 1

1

(As requested by @Ander Biguri, I've moved a solution that worked for me to a separete answer post. If anyone has an alternative/better approach, please feel free to post it as well)

Well, it seems that this question was asked here before. (perhaps formulated differently though?) I've managed to solve my issue using the following code:

sf = sfroot()
block = sf.find('Path','my_system/my_func','-isa','Stateflow.EMChart');
block.Script = sprintf('function y = fcn(u)\n%%#codegen\n\ny = 2 * u;')
Sign up to request clarification or add additional context in comments.

1 Comment

The primary thing to note is that a MATLAB Function block is a Stateflow block (or at least a part of one) in disguise. Hence the needs to use Stateflow API functionality to manipulate the block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.