Search code examples
matlabvectordynamic-memory-allocation

Dynamic memory allocation in MATLAB


I have two questions:

  1. What is the MATLAB equivalent of C's realloc()? Is that reshape()?
  2. How can I initialize a MALTAB vector that can be used to incrementally add new elements of object/struct type?

For instance, my_vector = zeros(1, N) cannot be used in case of objects/structs, right?


Solution

  • In MATLAB memory allocation is done automatically. I.e., adding elements to a vector automatically performs a realloc

    x = [ 1 2 3 ];
    x(4) = 4;  % performs realloc
    % now x == [1 2 3 4]
    
    x(2) = []; % deletes element 2
    % now x == [1 3 4]
    

    To create an array of objects I used repmat in the past. Since an object in the general case needs to be constructed from some data, I found the replication is often the best if nothing else is known about a class. To create an 2x3x4 array of default constructed objects of class CLS, use

    x = repmat( CLS(), [ 2 3 4] )
    

    I found this more appropriate than writing

    x = CLS();
    x(2,3,4) = CLS();
    

    which probably also would work but is awkward to read and probably could have subtle bugs if the class is not implemented correctly.

    structs can be created also with repmat, or, alternatively, by providing cell arrays to the struct constructor function, e.g.,

    x = struct( 'a', { 1 2 3}, 'b', { 5 6 7} );
    % now x is a 1x3 struct array