Clear Filters
Clear Filters

Memory management - variable size array

4 views (last 30 days)
I'm reading Yair Altman's Accelerating MATLAB® Performance book (2015 edition) and and on pg. 429 it states " Variable-sized arrays are required if we use functionality such as the find function or logical indexing." and "Variable-sized arrays that have an upper size limit are either statically or dynami cally allocated, depending on the coniguration for dynamic allocation. (...) Variable-sized arrays with unbounded maximal size are the least eficient. They are always allocated on the heap at run time, using dedicated internal functions. The allocation and reallocation costs in this case are maximal."
My questions are:
  1. Is variable sized array what i think it is i.e. a variable (e.g. and array) which does change size during the execution of the program like
A=[];
For i=1:100
A(end+1)=i;
end
or somehow one has to explicitly write that my X variable should be considered fixed-sized.
2. If it is the former then why an array has to be fixed-size for the find function or indexing?
(I think I understand what is heap and stack memory, and when to use which in languages where you can explicitly do that like C and C++)
(Also if one has good detailed articles or blog posts considering matlab's memory management, I would be glad if you could share them.)

Accepted Answer

Walter Roberson
Walter Roberson on 25 Feb 2024
At the MATLAB level, nearly everything is a variable-sized array. There are relatively few objects that enforce fixed-array limits behaviour, and those objects are mostly treated as variable-size internally. (There is the possible exception for "system objects" -- they are possibly treated internally as fixed size.)
The concern about variable-sized array compared to fixed-size array is relevant for Simulink and Embedded Coder and MATLAB Coder.
  2 Comments
Adrián László Szemenyei
and variable-sized arrays are stored in the heap, thus MATLAB seldomly uses the stack?
Walter Roberson
Walter Roberson on 25 Feb 2024
MATLAB variables are not normally stored in the stack, but variables in MATLAB Function Blocks (for Simulink) are generally stored in the stack.
MATLAB keeps a pool of "small blocks"; I no longer recall whether those blocks are 512 bytes or 1024 bytes. These blocks are in a reserved area of memory; it would be incorrect to call it a heap.
MATLAB keeps a heap of larger blocks.
We figure that MATLAB also allocates individual virtual memory zones for "sufficiently large" blocks, so that deallocating the variable has the effect of returning the memory to the operating system (which is something that does not happen to variables on the heap.)

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!