Main Content

GenerateMATLABFunction Blocks from Symbolic Expressions

UsingmatlabFunctionBlock, you can generate a MATLAB®Function block. The generated block is available for use in Simulink®models, whether or not the computer running the simulations has a license for Symbolic Math Toolbox™.

Generate and Edit a Block

Suppose, you want to create a model involving the symbolic expressionr = sqrt(x^2 + y^2). Before you can convert a symbolic expression to a MATLAB Function block, create an empty model or open an existing one:

new_system('my_system') open_system('my_system')

Create a symbolic expression and pass it to thematlabFunctionBlockcommand. Also specify the block name:

symsxyr = sqrt(x^2 + y^2); matlabFunctionBlock('my_system/my_block', r)

If you use the name of an existing block, thematlabFunctionBlockcommand replaces the definition of an existing block with the converted symbolic expression.

你可以打开和编辑生成的块。打开a block, double-click it.

function r = my_block(x,y) %#codegen r = sqrt(x.^2+y.^2);

Tip

Some symbolic expressions cannot be represented using MATLAB functions.matlabFunctionBlockcannot convert these symbolic expressions, but issues a warning. Since these expressions might result in undefined function calls, always check conversion results and verify results by running the simulation containing the resulting block.

Control the Order of Input Ports

matlabFunctionBlockgenerates input variables and the corresponding input ports in alphabetical order from a symbolic expression. To change the order of input variables, use thevarsoption:

symsxymu = sym('mu'); dydt = -x - mu*y*(x^2 - 1); matlabFunctionBlock('my_system/vdp', dydt,'vars', [y mu x])

Name the Output Ports

By default,matlabFunctionBlockgenerates the names of the output ports as the wordoutfollowed by the output port number, for example,out3. Theoutputoption allows you to use the custom names of the output ports:

symsxymu = sym('mu'); dydt = -x - mu*y*(x^2 - 1); matlabFunctionBlock('my_system/vdp', dydt,'outputs',{'name1'})