- Generate two specializations of ‘sum’, one where ‘parameterA’ is of size [:2272 x :16 x 2 x :16], the other where it is of size [:16 x 2 x :2272 x :16]
- Generate one specialization of 'sum' where ‘parameterA’ is of size [:2272 x :16 x :2272 x :16]
Why do I get the MATLAB Coder error 'Computed maximum size exceeds maximum allowed number of elements' when calling 'sum' on an array?
조회 수: 4 (최근 30일)
이전 댓글 표시
MathWorks Support Team
2024년 1월 26일
편집: MathWorks Support Team
2025년 11월 10일 11:59
When using MATLAB Coder in MATLAB R2023b to generate from the following code:
definitionA = coder.typeof(double(1),[2272, 16, 2, 16],[1 1 1 1]);
parameterA = coder.typeof(definitionA);
with 'DynamicMemoryAllocation' set to 'Off', I encounter the following error:
Computed maximum size exceeds maximum allowed number of elements (134217728).
The computed size is [:2272 x :16 x :2272 x :16].
According to the error message, it appears the third dimension of 'parameterA' is being expanded to match that of the first dimension.
This behavior can be traced to the 'sum' function on the following line in 'libraryA.m':
n = squeeze(sum(~isnan(parameterA),[2 3]));
Is this behavior expected?
채택된 답변
MathWorks Support Team
2025년 11월 10일 0:00
편집: MathWorks Support Team
2025년 11월 10일 11:59
When you call:
sum(~isnan(parameterA), [2 3])
or similarly:
sum(parameterA, [2 3])
MATLAB uses type inference to determine the data type and size of the input to the ‘sum’ function (or similar functions such as 'mean'). There are two ways in which type inference might interpret these calls (the colon before each number means that the dimension is variably sized):
In this case, type inference decided to generate one specialization where ‘parameterA’ has size [:2272 x :16 x :2272 x :16]. This is the smallest statically-allocated array that can hold any possible runtime value for this variable, i.e. it can hold both [:2272 x :16 x 2 x :16] and [:16 x 2 x :2272 x :16] sized arrays. In general, it is not possible to program around this heuristic in a practical way.
While this behavior is expected, it may appear counterintuitive. An enhancement request has been submitted to our development team to improve the error message for a future release.
As of MATLAB R2023b, multiple workarounds are available:
1.Turn on Dynamic Memory Allocation. Please refer to the following documentation pages:
for details on configuring this setting.
2. Set ‘variable_dims’ to false for the 3rd dimension:
definitionA = coder.typeof(double(1),[2272, 16, 2, 16],[1 1 0 1]);
3. Use nested function calls:
sum(sum(parameterA, 2), 3)
Due to another subtlety in 'sum', this will prevent Coder from anticipating an array of size [:2272 x :16 x :2272 x :16].
댓글 수: 0
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!