Work Around Language Limitation: Code Generation Does Not Support Object Arrays
Issue
In certain situations, your MATLAB® algorithm uses an array of objects that are instances of the same class. But code generation does not support object arrays. When attempting to generate code for such MATLAB code, you get this or a similar error message:
Code generation does not support object arrays.
Possible Solutions
Use Cell Array of Objects
Code generation supports cell arrays of objects. In your MATLAB code, represent the collection of objects by using a cell array instead of an array.
For example, suppose that your MATLAB algorithm uses the class Square
:
classdef Square properties(Access = private) side end methods(Access = public) function obj = Square(side) obj.side = side; end function area = calculateArea(obj) area = obj.side^2; end end end
The function addAreas
constructs and uses a 1
-by-3
array of Square
objects:
function y = addAreas(n) obj = Square(0); collection = [obj obj obj]; % collection is an array for i = 1:numel(collection) collection(i) = Square(n + i); end y = 0; for i = 1:numel(collection) y = y + collection(i).calculateArea; end end
Attempt to generate a MEX function for addAreas
. Code generation fails
because the local variable collection
is an object
array.
codegen addAreas -args 0 -report
Code generation does not support
object arrays.
Redefine collection
to be a cell array instead. Modify the code to use cell array indexing to index into collection
. Name the modified function addAreas_new
.
function y = addAreas_new(n) obj = Square(0); collection = {obj obj obj}; % collection is a cell array for i = 1:numel(collection) collection{i} = Square(n + i); end y = 0; for i = 1:numel(collection) y = y + collection{i}.calculateArea; end end
Attempt to generate a MEX function for addAreas_new
. Code generation succeeds and produces addAreas_new_mex
.
codegen addAreas_new -args 0 -report
Code generation successful: View report
Verify that addAreas_new
and addAreas_new_mex
have the same runtime behavior.
disp([addAreas_new(0) addAreas_new_mex(0)])
14 14
For Assignment with Nonscalar Indexing, Use Curly Braces and deal
Suppose that your original MATLAB code performs assignment to the array of objects by using nonscalar indexing. For example, you might add this line after the first for
loop in the addAreas
function:
collection(1:2) = [Square(10) Square(20)];
In the modified function addAreas_new
, index into the corresponding cell array by using curly braces {}
and perform assignment by using the deal
function. Replace the above line by:
[collection{1:2}] = deal(Square(10),Square(20));