Clear Filters
Clear Filters

Why do I get the error "Non-constant indexing into a heterogeneous cell array is not supported in code generation" when my function takes a cell array input with character vectors of varying length?

14 views (last 30 days)
I use MATLAB R2023a and I have a cell array with character vectors of varying length in the base workspace:
n=1000;
cellArray = cell(1,n);
for i=1:n
cellArray{i} = sprintf('String %d',i);
end
I am trying to read this cell array into my Simulink model using a MATLAB Function block with this code below, where the index 'idx' is a block input (runtime variable) and 'out' will be an output string signal:
function [out] = fcn(idx, cellArray)
out = string(cellArray{idx});
end
But I get this error when I try to run my model:
Non-constant indexing into a heterogeneous cell array is not supported in code generation.
The same error will occur if I try to generate code from a MATLAB function with this code using MATLAB Coder.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 13 Nov 2023
Edited: MathWorks Support Team on 13 Nov 2023
This is a current limitation of the underlying code generation functionality. Runtime indexing into a heterogeneous cell array is not supported as mentioned in the documentation below:
To work around this, create a local copy of the 'cellArray' variable as shown in the code below:
function [out] = fcn(idx, cellArray)
c = cellArray;
out = string(c{idx});
end
The function input cannot be changed from heterogeneous to homogeneous, while the local copy can.
The "loadStringsFromCellArray.zip" file attached above contains the example and solution.

More Answers (0)

Categories

Find more on Simulink 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!