By Adam L. Lambert, "Zero to Matlab", section 12.
Structs are more complex than tables. In this section we'll walk through some basic examples to give you a feel for how they behave. Again I will work in the Command Window. Structs store values in elds. Each field has a name. We access the fields using the same dot notation that was used in the table section.
The simplest method for creating a struct is to define it using dot notation.
c.a = 1
Now we have a struct named c in the workspace. We can see in the Command Window that it has a field named "a" which has a value of 1. Now add another field:
c.b = 2
Now the struct has two fields, a and b.
We can use the value from a field in an expression like this.
y = 2*c.b
The fields of a struct can be any variable type. Let's add an array to c.
c.temp = [100,200,300]
And now a string.
c.name = 'Harvey'
We can actually store an array of structs. Let's add a second element.
c(2).a = 3
Now in the Command Window you will see that we have a 1x2 struct array and the name of each field is reported. Since we have only assigned on field in the second element, then the other fields will be blank.
Check for yourself.
At this point we need to discuss two issues that can trip people up. The first is that the fields in each element do not have to be the same variable type. I can assign a string to c.temp and a double to c.name.
c(2).temp = 'Hot!'
Now print the temp field for the whole array in the Command Window.
First we see the temperature array assigned to the default variable name. Next we see the string. This is because MATLAB is looping through the struct and printing them one at a time. If we try to assign it to a variable then we will only get the first element. In this case it will be the array.
y = c.Temp
If we want the field from the second element, then we have to index the struct.
y = c(2).temp
The other issue with struct arrays is that we cannot use them directly in calculations. For example, the a field has only individual numbers in both elements. However the following command will generate an error.
y = 2*c.a
This error tells us that we are using too many numbers with the multiplication operator. Again, the struct must be indexed for this calculation to work.
y = 2*c(1).a