MATLAB: Can I eliminate the extra copy of a variable that is created in the generated code when using a “MATLAB function” block with a “Data Store Read” block as the input

Embedded Coder

I have a "Data Store Read" block as the input to a "MATLAB function" block.
This is the function in my "MATLAB function" block:
function myMFunction(myDataStore)
coder.ceval('myCFunction', myDataStore);
Generating code results in the following:
tmp[0] = myDataStore[0];
tmp[1] = myDataStore[1];
tmp[2] = myDataStore[2];
myCFunction(tmp);
instead of:
myCFunction(myDataStore);

Best Answer

  • To generate code without an extra copy of the variable, you will have to change some settings. Here are the steps to follow:
    1) Open the "Ports and Data Manager" as follows: Double click the "MATLAB function" block to open the function in MATLAB. In the top toolbar, select "Edit Data" found in the "Simulink" section.
    2) In the "Ports and Data Manager" dialog window, change myDataStore to be a Data Store instead of an input to the MATLAB function block.
    3) Declare myDataStore as a global inside the MATLAB function as follows:
    >> global myDataStore;
    4) Wrap myDataStore inside a call to coder.ref:
    >> coder.ceval('-global','myCFunction', coder.ref(myDataStore));
    You can refer to the following documentation page for more information about "coder.ref":
    5) Comment out the "Data Store Memory Read" block that is currently connected to the "MATLAB function" block.
    6) Double click the "Data Store Memory" block and go to the signal attributes tab. The signal type cannot be set to "auto". Change it accordingly. For example:
    7) Now you can generate code without the extra copy of the variable.