Extending variable in MATLAB Coder causes function body to disappear

2 views (last 30 days)
I have a MATLAB function which changes the size of a variable after it is defined.  The variable is marked as variable size with the "coder.varsize" function, and MATLAB Coder allows the size of the variable to change:
function v = test_fcn()
coder.varsize("v", [1 2]);
v = 0;
v(end + 1) = 1;
rand;
end
When I compile this function using MATLAB Coder with the command
>> codegen -config cfg -o generated_code test_fcn
no warnings are emitted but the body of the resulting C function is empty:
void test_fcn(const double v_data[], const int v_size[2])
{
(void)v_data;
(void)v_size;
/* A check that is always false is detected at compile-time. Eliminating code
* that follows. */
}
The behavior of the function is now incorrect in two ways: (1) the return value is incorrect and (2) the code no longer calls "rand" and so no longer changes the state of the random number generator.
How do I make this code compile correctly?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 26 May 2023
Changing sizes of variables by indexing past their size causes a known limitation, which is documented here:
https://www.mathworks.com/help/releases/R2022b/fixedpoint/ug/limitations-with-variable-size-support-for-code-generation.html#bq1h2z9-86
This specific case of indexing using "end + 1" will compile correctly in R2023a when the "Enable variable-sizing" option is set, as described here:
https://www.mathworks.com/help/releases/R2023a/coder/ug/grow-arrays-using-end-plus-one-indexing.html
In general, this issue is only caused when variables are implicitly resized using indexing operations, so the issues can be resolved by either (a) initializing the variable to the largest required size or (b) extending the variable explicitly without using indexing.
For example, the given code could be converted to the following, which compiles correctly:
function v = test_fcn()
coder.varsize("v", [1 2]);
v = zeros(1, 2); % Initialize 'v' at its maximum size, in this case a 1x2 matrix
v = [v 1]; % Was `v(end + 1) = 1`
rand;
end
An alternative solution is to pre-allocate the variables to their maximum size.  For example, the given code could be converted to the following:
function v = test_fcn()
coder.varsize("v", [1 2]);
v = zeros(1, 2); % Initialize 'v' at its maximum size, in this case a 1x2 matrix
v(2) = 1;
rand;
end

More Answers (0)

Categories

Find more on MATLAB Coder in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!