matlabstructurevectorizationpre-allocation

Preallocation of nested structure array


I am trying to pre-allocate a uniformly nested structure array.

I'm currently using for loops to allocate values to the array, but I understand that this is slow if the array has not been pre-allocated.

The structure I am trying to achieve is generated by the following code:

aLength = 10;
bLength = 20;

a = struct('b',{});
b = struct('c',{0},'d',{0});
for i = 1:aLength
    for j = 1:bLength
        a(i).b(j) = b;
    end
end

Where the zero values will be replaced later in a for loop.


Solution

  • The following approach gives identical results to your loop:

    aLength = 10;
    bLength = 20;
    
    b(1:bLength) = struct('c', {0}, 'd', {0});
    a(1:aLength) = struct('b', b);
    
    a
    a(1)
    

    Output:

    a =
      1x10 struct array containing the fields:
        b
    
    ans =
      scalar structure containing the fields:
        b =
          1x20 struct array containing the fields:
            c
            d
    

    A small test increasing aLength and bLength shows a drastic speed-up from the loop version to the shown approach.

    Hope that helps!