You are on page 1of 2

Associated with a field.

So we have a field and value relationship,


where field is a descriptive term describing what
you're storing at that value.
And we'll see examples of this below.
For example, if we look at this struct here,
we're going to say the field would be "name"
and then we're going to list the classes associated
with this name.
Another field is "units" and you get the list
of the units associated.
And the third field would be "grade."
Structures can be arranged in N-dimensional arrays, which
are called structure arrays.
In MATLAB, this is very easy to create a structure array.
First, you will initialize your variable to be an empty struct.
And there's two ways we see that we can construct them.
The first such way would be to say your variable name,
dot, with the field name, is equal to the field value.
So if we look at the example below,
we would say classes is equal to struct.
Classes dot name is equal to this.
Part here, classes dot units is equal to {one, one}.
If we would like to have it more streamlined
and one line of code, we see in this example
that you can actually give all of your fields
with a comma next to it with their associated values.
So whichever way you prefer, both are equivalent.
To access data within the structure array,
we simply use the parentheses.
And to access a field, use the dot notation.
So here, we see classes of two is
going to give us every entry associated
with two in the struct.
So we'll see the name is CME292 for units 1 and for grade pass.
If we did classes dot name, that would give us
CME192 and CME292.
And there are other built-in features,
which makes it very easy to access,
whether something is a field or not
and also to get the names of all of your fields.
So you might wonder, do we need to have the field names known
ahead of time?
That is not necessarily needed in MATLAB.
They do not need to be known in advance.
And in general you can generate the field names
during computation.
One particular application of this
would be if you're reading in the field names,
let's say from a file where they need to be dynamically read in
and not known at compute time.
So in the simple body of code here we see an example of this.
We set "s" to be an empty struct.
And we're going to be naming its field, "looping over i."
So what is this piece of code doing here?
I'm concatenating two strings.
Remember the horzcat function
works on any datatype.
So what I'm saying here is we have "P"
and I'm converting a numeric number "i" to a string.
And this will put it together as such.
So we see as we loop through on the first iteration, num2str
"i" will give us P1 and we're printing "i."
So here we have our value--
or field is P1 and the value is 1.

You might also like