Structures, or structs, are a basic data type in MATLAB/Octave that can be used to organize and combine multiple properties into one common data structure. The properties on a struct, also referred to as fields, can be of different types and of varying sizes. Each of the properties on a struct can then be accessed and operated on as they normally would. Structs have a multitude of uses in MATLAB/Octave and are very much akin to dictionaries for those that are more familiar with Python.

In this article, I introduce the basics of structs and then share what I believe to be some of the most useful “tips” for working with them. In particular, I cover the following topics:

  • Dynamic property access and the _filednames() _function
  • Working with arrays of structs
  • Considerations for writing efficient code using structs

Source code for all of the examples can be found in the GitHub repository. It is important to note that MATLAB and Octave display structs quite differently, so you may see some differences depending on which application you run the code with. In this tutorial, I have run all of the examples with Octave to make things as accessible as possible.

The Basics

Structs in MATLAB/Octave are managed dynamically, so we can add and remove new properties at any time. The easiest way to create a struct is to use the struct() command to create an empty struct and the dot operator to populate it. Here is a simple example.

s = struct(); % create an empty struct
s.val1 = 100; % add a scalar
s.val2 = 0 : 25 : 100; % add a vectorize
s.val3 = randn( 2, 3, 5 ); % add an ND array
s.char1 = 'This is a character string'; % add a character string
s.cell1 = { 100, 300, '5', 'abc' };  % add a cell array
disp( s );
scalar structure containing the fields:
val1 =  100
    val2 =
0    25    50    75   100
val3 =
ans(:,:,1) =
-0.49715   0.32621  -0.81624
      -0.34628   1.85946   0.29556
ans(:,:,2) =
-0.32521   0.44471   2.40743
      -0.97223  -0.24240   0.39241
ans(:,:,3) =
-1.63085  -0.34078   0.46239
       0.48026  -0.45361   1.62214
ans(:,:,4) =

       0.523431  -0.576770  -0.028377
      -1.035780   0.093593  -2.001485
ans(:,:,5) =
0.30492  -2.05388   0.13755
      -0.98662  -1.36354  -0.43432
char1 = This is a character string
    cell1 =
    {
      [1,1] =  100
      [1,2] =  300
      [1,3] = 5
      [1,4] = abc
    }

We can now access any of the newly added properties using the corresponding field names. For example, let’s access the 2nd element of “val2”.

>> disp( s.val2(2) );

25

Or we could access the last element of “cell1”.

>> disp( s.cell1{end} );

abc

In fact, we can now access and modify all of the properties just like we would if they weren’t on the struct. Let’s add a new value to “cell1”.

>> s.cell1{ end+1 } = 'I am new!';
>> disp( s.cell1 );

{
  [1,1] =  100
  [1,2] =  300
  [1,3] = 5
  [1,4] = abc
  [1,5] = I am new!
}

Or let’s remove some values from “val2”.

>> disp( s.val2 );

0    25    50    75   100
>> s.val2( 2:3 ) = [];
>> disp( s.val2 );
0    75   100

Finally, using the rmfield() function, we can completely remove fields from a struct. For example, let’s create a new struct named “s2” and remove all of the fields except for “val1”. The syntax for this is: sOut = rmfield( s, { ‘name1’, ‘name2’, etc… } ), where “sOut” could be “s” if we wanted to overwrite the original struct, and the cell array contains the name of all fields that we would like to remove.

>> s2 = rmfield( s, { 'val2', 'val3', 'char1', 'cell1' } );
>> disp( s2 );

scalar structure containing the fields:
val1 =  100

This was a rather fast walk through of the most basic uses of structs. If you are brand new to structs, it is probably worth spending a little bit of time looking through the MATLAB documentation. The rest of this article will touch on some of the more advanced, or perhaps just lest obvious, ways of working with structs.

Dynamically accessing properties and the fieldnames() function

Another very useful feature of structs is that you can build arrays of them. These arrays behave mostly like any other array, however, there is some additional care that must be taken to populate them. In particular, each element in an array of structs must have all of the same properties. They can be empty, but all of the properties must exist before multiple structures can be concatenated into an array.

To start with a simple example, lets set the second element of “s3” to another copy of itself.

>> s3(2) = s3;
>> disp( s3 );

1x2 struct array containing the fields:
noodles
    dexter
    ron
    greg

Now we can see that there is a 1x2 array of structs. Note that this worked since both of the structs had exactly the same properties.

Structure arrays act just like any other arrays and can be accessed using (). As an example, let’s update the “noodles” field on the first struct to be equal to twice the current value.

>> s3(1).noodles = s3(1).noodles * 2;
>> disp( s3(1).noodles );

62
>> disp( s3(2).noodles );
31

We can also remove elements from a structure by setting an element to an empty value.

>> s3(1) = [];
>> disp( s3 );

scalar structure containing the fields:
noodles =  31
    dexter =  11
    ron =  46
    greg =  28

Note that the above output shows that we once again have a scalar structure. since we have removed the first element of the structure array.

Finally, it can also be convenient to collect values across an array of structs. For example, let’s say we had an array of structs containing images with geo-tags and we were interested in looking at the locations for all of the images. We can collect these values into an array by capturing the struct output between square brackets [].

Let’s demonstrate this with another example. First, we will build 10 structs, each with “img”, “lat’, and “lon” properties. Note that within the loop, a temporary variable is used to fully populate each struct before it is added to the array. This is actually unnecessary in this case since I am pre-allocating the structure memory by looping backwards; however, in general, it is a good practice because it will ensure that all of the fields exist before you attempt to concatenate the structures.

#coding #matlab #programming #octave #visual studio code #visual studio

Structures in MATLAB/Octave
1.65 GEEK