Why does the memory allocation for handle class objects in a cell array cause an error in a loop?
10 views (last 30 days)
Show older comments
MathWorks Support Team
on 23 Mar 2023
Answered: MathWorks Support Team
on 24 Mar 2023
I am unable to generate C++ code for an M-file that allocates memory for a handle class cell array during a loop using MATLAB R2021b.
The class that I am using is defined below. It has a property named "Value" that is assigned by an argument, or by the class function "setValue":
classdef BasicClass < handle %#codegen
properties
Value;
end
methods
function obj = BasicClass(val)
if nargin == 1
obj.Value = val;
end
end
function obj = setValue(obj, input)
obj.Value = input;
fprintf( 'set.Prop1 method called. Prop1 = %f\n', obj.Value );
end
end
end
Here is the relevant code that I am trying to generate code for:
Nodes = cell(1, Nobs);
for nobs = 1:Nobs
Nodes{nobs} = BasicClass(nobs);
end
tmp = Nodes{5};
"BasicClass" is a class that inherits handle, "Nobs" is a variable that I'm setting at my entry point (I want to set "Nobs" at the cli interface for my C++). I'm receiving this error when running my script to generate C++ code:
### Compiling function(s) my_entry_point ...
### Generating compilation report ...
??? Cannot allocate this handle object. For code
generation, a handle object allocated inside a loop
cannot be referenced outside of the loop.
How can I resolve this error?
Accepted Answer
MathWorks Support Team
on 23 Mar 2023
The MATLAB coder must statically allocate memory for handle class objects, and allocating in a loop prevents static memory allocation. The 'Nodes' variable should be pre-allocated not only in size, but also in data type.
A workaround is to use "repmat" on a single cell entry to ensure the variable-sized cell array passes the define-it-before-using-it analysis. Then, use a loop to adjust the values of each handle-class object in the array:
% Allocate for a cell array of handle classes
Nodes = repmat({BasicClass(1)}, 1, Nobs);
% Variable-sized for loop
for nobs = 2:Nobs
% Set the object as you'd like.
setValue(Nodes{nobs}, nobs);
end
tmp = Nodes{5};
0 Comments
More Answers (0)
See Also
Categories
Find more on MATLAB Classes 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!