1

Is there anyway to allot a fixed chunk of memory for a growing/decreasing array in a loop? I know the range of sizes it can have, i.e. the min and max dimensions.

I could just allot a matrix of max size as follows, A = zeros(max,max); but here's the problem with that approach. I have matrix multiplication and inverse operations inside the loop. On top of that, I am using slicing operation (complete row/column selections)

A[:,i]  = data(i).x;
B = A\P; 
C = A*W;

The allocation of maximum size does not go well these operations (size mismatch error).

So, I am trying to allocate a memory chunk corresponding to a max dimension, but want to utilize only a part of it.

I know this can be achieved using loops for matrix operations, instead of vector operations in Matlab but that would be inefficient. (in fact I am not sure how the inverse operation would be implemented in a loop).

Any help is appreciated.

User 10482
  • 855
  • 1
  • 9
  • 22
  • No, you cannot control the memory size and array size independently in MATLAB. MATLAB does allocate a larger space for an array if it increases incrementally in a loop, see here: https://stackoverflow.com/questions/48351041/matlab-adding-array-elements-iteratively-time-behavior/48353598#48353598 – Cris Luengo Nov 16 '19 at 14:48
  • There is no simple solution, especially when it comes to matrices. For a vector you could index the part you actually want, but indexing a matrix on both dimensions is significant slower (non consecutive memory). Before you waste your time, did you actually profile the code to see if the growing / shrinking is critical to the performance? With some matrix operations inside, I could imagine it does not really matter. – Daniel Nov 16 '19 at 16:30
  • Thank you guys for the replies. @Daniel It needs to grow and shrink. I get the data in batches (different sizes) and update the previous calculation accordingly. I can potentially cut the data to the minimum size every batch but that wouldn't be acceptable to some people. – User 10482 Nov 16 '19 at 18:01
  • @Cris That brings up an interesting point. If Matlab doubles the allocated memory, only if we could access this 2x factor and customize it we could allocate custom memory size. – User 10482 Nov 16 '19 at 18:03
  • 1
    But note that growing a matrix in height will always require data copy, it is only growing a matrix width or growing a vector that can make use of that type of optimization. – Cris Luengo Nov 16 '19 at 18:51

0 Answers0