2
votes

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?

1
This is an interesting question. Instead of editing the question, post an answer with whatever helped you.Ander Biguri
@Ander Biguri: Done ;)maddouri

1 Answers

1
votes

(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;')