How do I Initialize a Struct Array in Matlab/Octave?

July 9, 2012 in Matlab, Octave

Suppose that you want to create a 2D array whose entries are the structures:

geoLocationStruct = struct('latitude', nan, 'longitude', nan);

The easiest (in my opinion) way to to this is using the syntax:

geoLocation(128,128) = geoLocationStruct;

This will initialize the element (128,128) of a 2D array to the geoLocationStruct structure just defined, causing the allocation of a struct array like:

geoLocation =

  128x128 struct array containing the fields:

    latitude
    longitude

But what happens to the elements with indices different from (128,128)? Apparently, the behavior of Matlab differs from the behavior of Octave. In Matlab we have:

>> geoLocation(8,127) = 

ans =

    latitude: []
    longitude: []

This makes sense: an element that is not initialized has structure entries that are empty. The struct array consumes 262496 bytes (as it can be found typing whos geoLocation): this also makes sense, since space is reserved for 16384 entries each one 16 bytes long (2 doubles each one taking 64 bits or, equivalently, 8 bytes). However, in Octave (GNU Octave Version 3.4.3) we have that:

> geoLocation(8,127)
ans =

  scalar structure containing the fields:

    latitude =

error: octave_base_value::print (): wrong type argument `<unknown type>'

    longitude =

error: octave_base_value::print (): wrong type argument `<unknown type>'

This does not look too good… Also, inspecting the memory consumption with whos geoLocation, we get:

Variables in the current scope:

  Attr Name             Size                     Bytes  Class
  ==== ====             ====                     =====  ===== 
       geoLocation    128x128                       16  struct

Total is 16384 elements using 16 bytes

This means that only the memory for element (128, 128) was allocated. Any time we add a new element, the memory for the corresponding structure will be allocated.
To learn more about structure initialization in Matlab you may want to give a look to Loren’s post.