Getting Started | ![]() ![]() |
Structures
Structures are multidimensional MATLAB arrays with elements accessed by textual field designators. For example,
S.name = 'Ed Plum'; S.score = 83; S.grade = 'B+'
creates a scalar structure with three fields.
S = name: 'Ed Plum' score: 83 grade: 'B+'
Like everything else in MATLAB, structures are arrays, so you can insert additional elements. In this case, each element of the array is a structure with several fields. The fields can be added one at a time,
S(2).name = 'Toni Miller'; S(2).score = 91; S(2).grade = 'A-';
or, an entire element can be added with a single statement.
S(3) = struct('name','Jerry Garcia',... 'score',70,'grade','C')
Now the structure is large enough that only a summary is printed.
S = 1x3 struct array with fields: name score grade
There are several ways to reassemble the various fields into other MATLAB arrays. They are all based on the notation of a comma separated list. If you type
S.score
S(1).score, S(2).score, S(3).score
This is a comma separated list. Without any other punctuation, it is not very useful. It assigns the three scores, one at a time, to the default variable ans
and dutifully prints out the result of each assignment. But when you enclose the expression in square brackets,
[S.score]
[S(1).score, S(2).score, S(3).score]
which produces a numeric row vector containing all of the scores.
ans = 83 91 70
S.name
just assigns the names, one at time, to ans
. But enclosing the expression in curly braces,
{S.name}
creates a 1-by-3 cell array containing the three names.
ans = 'Ed Plum' 'Toni Miller' 'Jerry Garcia'
char(S.name)
calls the char
function with three arguments to create a character array from the name
fields,
ans = Ed Plum Toni Miller Jerry Garcia
![]() | Characters and Text | Scripts and Functions | ![]() |