How do I pass arrays by reference to an Embedded MATLAB subfunction from an Embedded MATLAB script in Simulink 7.1 (R2008a)?
6 views (last 30 days)
Show older comments
I have written an Embedded MATLAB script in which the main function calls a subfunction and passes an array as one of the arguments. I wish to ensure that the arguments are passed by reference and not passed by value when the Embedded MATLAB script is compiled into C code.
Accepted Answer
MathWorks Support Team
on 16 Mar 2011
If an input argument passed to an Embedded MATLAB subfunction is not modified anywhere inside the sub-function, it is passed by reference; but if the input argument is modified, it is passed by value.
If you need to pass the input argument as a reference and change it inside the sub-function, include the name of the input in the list of outputs in the function declaration. For example, in the following example if you want "z" to be passed by reference, include "z" in the list of output arguments as shown below:
%z is a structure with two fields val1 and val2
function z = sub_fun(z)
z.val1=z.val1+9;
z.val2=z.val2+18;
The above "z = sub_fun(z)" optimization only applies to subfunctions. It does not apply at the top level, which includes signal inputs to an Embedded MATLAB block in Simulink and the inputs to a MEX function generated by EMLC or EMLMEX in MATLAB.
You do not get pass-by-reference functionality if you declare the function as follows:
function NOTZ = sub_fun(z)
and invoke it in the following way:
z = sub_fun(z);
The attached model "eml_subfunction_passbyref.mdl" contains an Embedded MATLAB function block with a sub-function " sub_fun" explained above. The attached generated file "eml_subfunction_passbyref.c" illustrates how 'z' is passed as reference in to the sub function.
0 Comments
More Answers (0)
See Also
Categories
Find more on Block Libraries 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!