Editing the Code of a “MATLAB Function” Block in Simulink Programmatically

半世苍凉 提交于 2019-12-22 22:21:24

问题


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:


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


来源:https://stackoverflow.com/questions/42263697/editing-the-code-of-a-matlab-function-block-in-simulink-programmatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!