MATLAB: How to grow MATLAB variables by indexing out of bounds in a way that is supported by MATLAB Coder 2.2 (R2012a)

boundscodecodergenerationgrowindexMATLABmatlab coderofoutsize;variables

In MATLAB, I can grow a variable by indexing out of bounds. By default, MATLAB will fill out any missing entries with zeros (as in the case of a numerical array). For example:
x = 1;
x(3,3) = 1
x =
1 0 0
0 0 0
0 0 1
When I try to generate code from such a function using MATLAB Coder, I receive an error:
??? Index expression out of bounds. Attempted to access element 3. The valid range is 1-1.
Is there any way to work around this?

Best Answer

In Release 2012b (R2012b) the following link to documentation throws some light on this topic:
Read below for any additional information:
The ability to grow variable sized arrays by indexing out of bounds is currently not supported with MATLAB Coder 2.2 (R2012a).
As a workaround, you can re-allocate the size of the variable to be "grown" and copy the old (smaller) variable in the appropriate dimensions.
For example, let us build a matrix in the following fashion:
1
1 2
2 2
1 2 3
2 2 3
3 3 3
... and so forth, up to a dimension of 5.
The way to do this is to declare the variable as a variable-sized array using the CODER.VARSIZE command.
% Declare 'x' as having a maximum size of [5 x 5].
coder.varsize('x',[5 5]);
% Loop through and increment the size of x at each step (up to a dimension
% of [5 x 5]). View the output to see what this function does.
x = 1;
for i = 2:5
temp = i*ones(i);
temp(1:i-1,1:i-1) = x;
x = temp;
end
This is supported with code generation and produces the following output:
ans =
1 2 3 4 5
2 2 3 4 5
3 3 3 4 5
4 4 4 4 5
5 5 5 5 5
For more information on the CODER.VARSIZE function, please refer to the following documentation:
<http://www.mathworks.com/help/toolbox/coder/ref/coder.varsize.html>