Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does MATLAB handle dynamic array allocation?

I'm not well versed in MATLAB and was curious about how it handles dynamic memory allocation under the hood?

One primary method is to allocate large chunks and more than is necessary so that you don't have to allocate for each new element added. In doing a bit of research, I saw a lot of people who personally managed their own large-chunk allocation (assuming they didn't know their final size) or did things like creating a maximum size, then trimming. An example is Undocumented MATLAB which advises you to perform block memory allocation yourself. I would have thought that a language like MATLAB would know to do it itself and I wouldn't be required to concern myself with issues like that. This implies to me if you try to append a single new element on to an array, MATLAB allocates new memory for only that single element, which is horribly inefficient.

My question is two-fold

  • For dynamic arrays, does MATLAB allocate in large chunks, and more memory than is necessary to save on computational efficiency, or does it allocate memory for only what is being concatenated?
  • If the former is the the case, is there a reason MATLAB chose to go with this design?
like image 778
zephyr Avatar asked Sep 24 '15 16:09

zephyr


People also ask

How does MATLAB allocate memory?

When you assign a numeric or character array to a variable, MATLAB allocates a contiguous block of memory and stores the array data in that block. MATLAB also stores information about the array data, such as its class and dimensions, in a small, separate block of memory called a header.

How do you handle dynamic arrays?

Elements can be added at the end of a dynamic array in constant time by using the reserved space until this space is completely consumed. When all space is consumed, and an additional element is to be added, the underlying fixed-sized array needs to be increased in size.

Does MATLAB support multidimensional array?

A multidimensional array in MATLAB® is an array with more than two dimensions. In a matrix, the two dimensions are represented by rows and columns. Each element is defined by two subscripts, the row index and the column index.


1 Answers

I recall at the Matlab Expo a few years ago they had a talk about things under development at HQ - one of which was automatic pre-allocation of memory.

There was no mention as to when this might be released or even if it would ever be.... And I have never heard mention of it since...

From my experience - I have always managed the dynamic allocation myself - and always noticed serious slow down if that part of the code had issues (i.e. the arrays were growing when I thought they shouldn't be...)

So I think its fair to say that you need to manage it yourself.

like image 99
matlabgui Avatar answered Nov 03 '22 02:11

matlabgui