MATLAB Coder generated MEX file throws an error that "Index exceeds matrix dimensions" although the code runs in MATLAB without error

I'm trying to use MATLAB Coder to generate C/C++ code for my MATLAB code. However, when I try to execute the MEX file generated by MATLAB Coder, it throws an error that for a specific variable that the index exceeds matrix dimensions:
>> myCode_mex
Index exceeds matrix dimensions. The array 'A' is empty and therefore has no valid indices.
The error stack points to the following MATLAB source code where I perform array extension:
n = length(A);
if n < buffSize
A(n+1) = data;
The same code however runs in MATLAB without any issues. Why does this happen?

 Accepted Answer

This is fundamental difference between MATLAB execution and code generation. Code generation does not support increasing the size of an array through left-hand-side indexing out-of-bounds (except in some circumstances where the index is exactly "end+1"). See the "Incompatibility with MATLAB in Matrix Indexing Operations for Code Generation" section in the following documentation:
Which states that "Code generation does not support increasing the size of an array over time.".

Try This Workaround:

If 'A' is variable-sized (due to coder.varsize in the constructor), the you can grow 'A' by assigning to it completely:
Instead of:
A(n+1) = data;
Use:
A = [A, data];

More Answers (0)

Products

Release

R2015b

Community Treasure Hunt

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

Start Hunting!