Provide Maximum Size for Variable-Size Arrays
To constrain array size for variable-size arrays, do one of the following:
Constrain Array Size Using assert StatementsIf the variable specifying array size is not a compile-time constant, use an
assertstatement with relational operators to constrain the variable. Doing so helps the code generator to determine a maximum size for the array.The following examples constrain array size using
assertstatements:
When Array Size Is Specified by Input VariablesDefine a function
array_initwhich initializes an arrayywith input variableN:function y = array_init (N) assert(N <= 25); % Generates exception if N > 25 y = zeros(1,N);
The
assertstatement constrains inputNto a maximum size of 25. In the absence of theassertstatement,yis assigned a pointer to an array in the generated code, thus allowing dynamic memory allocation.
When Array Size Is Obtained from Computation Using
Input VariablesDefine a function,
array_init_from_prod, which takes two input variables,MandN, and uses their product to specify the maximum size of an array,y.function y = array_init_from_prod (M,N) size=M*N; assert(size <= 25); % Generates exception if size > 25 y=zeros(1,size);
The
assertstatement constrains the product ofMandNto a maximum of 25.Alternatively, if you restrict
MandNindividually, it leads to dynamic memory allocation:function y = array_init_from_prod (M,N) assert(M <= 5); assert(N <= 5); size=M*N; y=zeros(1,size);This code causes dynamic memory allocation because
MandNcan both have unbounded negative values. Therefore, their product can be unbounded and positive even though, individually, their positive values are bounded.Tip
Place the assert statement on a variable immediately before it is used to specify array size.
Tip
You can use
assertstatements to restrict array sizes in most cases. When expanding an array inside a loop, this strategy does not work if the number of loop runs is known only at run time.
Restrict Concatenations in a Loop Using coder.varsize
with Upper BoundsYou can expand arrays beyond their initial size by concatenation. When you concatenate additional elements inside a loop, there are two syntax rules for expanding arrays.
Array size during initialization is not a compile-time
constantIf the size of an array during initialization is not a compile-time constant, you can expand it by concatenating additional elements:
function out=ExpandArray(in) % Expand an array by five elements out = zeros(1,in); for i=1:5 out = [out 0]; end
Array size during initialization is a compile-time
constantBefore concatenating elements, you have to declare the array as variable-size using
coder.varsize:function out=ExpandArray() % Expand an array by five elements out = zeros(1,5); coder.varsize('out'); for i=1:5 out = [out 0]; end
Either case leads to dynamic memory allocation. To prevent dynamic memory allocation in such cases, use
coder.varsizewith explicit upper bounds. This example shows how to usecoder.varsizewith explicit upper bounds:Example 1. Restrict Concatenations Using coder.varsize with Upper BoundsDefine a function,
RunningAverage, that calculates the running average of anN-element subset of an array:function avg=RunningAverage(N) % Array whose elements are to be averaged NumArray=[1 6 8 2 5 3]; % Initialize average: % These will also be the first two elements of the function output avg=[0 0]; % Place a bound on the argument coder.varsize('avg',[1 8]); % Loop to calculate running average for i=1:N s=0; s=s+sum(NumArray(1:i)); avg=[avg s/i]; % Increase the size of avg as required by concatenation end
The output,
avg, is an array that you can expand as required to accommodate the running averages. As a new running average is calculated, it is added to the arrayavgthrough concatenation, thereby expanding the array.Because the maximum number of running averages is equal to the number of elements in
NumArray, you can supply an explicit upper bound foravgin thecoder.varsizestatement. In this example, the upper bound is 8 (the two initial elements plus the six elements ofNumArray).Generate code for
RunningAveragewith input argument of typedouble:codegen -config:lib -report RunningAverage -args 2
In the generated code,
avgis assigned an array of size 8 (static memory allocation). The function definition forRunningAverageappears as follows (using built-in C types):void RunningAverage (double N, double avg_data[8], int avg_size[2])
By contrast, if you remove the explicit upper bound, the generated code dynamically allocates
avg.Replace the statement
coder.varsize('avg',[1 8]);with:
coder.varsize('avg');Generate code for
RunningAveragewith input argument of typedouble:codegen -config:lib -report RunningAverage -args 2
In the generated code,
avgis assigned a pointer to an array, thereby allowing dynamic memory allocation. The function definition forRunningAverageappears as follows (using built-in C types):void Test(double N, emxArray_real_T *avg)
Note
Dynamic memory allocation also occurs if you precede
coder.varsize('avg')with the following assert statement:Theassert(N < 6);
assertstatement does not restrict the number of concatenations within the loop.
Constrain Array Size When Rearranging a MatrixThe statement
out = reshape(in,m,n,...)takes an array,in, as an argument and returns array,out, having the same elements asin, but reshaped as anm-by-n-by-...matrix. If one of the size variablesm,n,.... is not a compile-time constant, then dynamic memory allocation ofouttakes place.To avoid dynamic memory allocation, use an
assertstatement before thereshapestatement to restrict the size variablesm,n,...tonumel(in). This example shows how to use anassertstatement before areshapestatement:Example 2. Rearrange a Matrix into Given Number of RowsDefine a function,
ReshapeMatrix, which takes an input variable,N, and reshapes a matrix,mat, to haveNrows:function [out1,out2] = ReshapeMatrix(N) mat = [1 2 3 4 5; 4 5 6 7 8] % Since mat has 10 elements, N must be a factor of 10 % to pass as argument to reshape out1 = reshape(mat,N,[]); % N is not restricted assert(N < numel(mat)); % N is restricted to number of elements in mat out2 = reshape(mat,N,[]);
Generate code for
ReshapeArrayusing thecodegencommand (the input argument does not have to be a factor of 10):codegen -config:lib -report ReshapeArray -args 3
While
out1is dynamically allocated,out2is assigned an array with size 100 (=10 X 10) in the generated code.Tip
If your system has limited memory, do not use the
assertstatement in this way. For ann-element matrix, theassertstatement creates ann-by-nmatrix, which might be large.
See Also
Topics
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)