MATLAB Tutorial
Chapter 7. Data structures and input assertion
7.1. User-defined data structures
Vectors and matrices are not the only means that MATLAB offers for grouping data into a
single entity. User defined data structures are also available that enable the programmer to
create variable types that mix numbers, strings, and arrays. As an example, let us create a
data structure that contains the information for a single student.
We will store the name, status (year and department), the homework and exam grades, and
the final class grade.
First, we can define a NameData structure to contain the name. Here, the "." operator, used in
the case of Structure.Field tells MATLAB to access the field named "Field" in the structure
"Structure".
NameData.First = 'John';
NameData.MI = 'J';
NameData.Last = 'Doe';
We now create a StudentData structure with a name field.
StudentData.Name = NameData;
We now initialize the rest of the structure.
StudentData.Status = 'ChE grad 1';
StudentData.HW = 10;
StudentData.Exam = linspace(100,100,3);
We can now view the contents of the structure
StudentData
StudentData.Name
StudentData.Exam
We can operate on the elements of a structure.
StudentData.Exam(3) = 0;
StudentData.Exam
StudentData.Name.First = 'Jane';
StudentData.Name
We can also create arrays of structures
num_students = 5;
for i=1:num_students
ClassData(i) = StudentData;
end
ClassData
ClassData(2)
Structures can be passed as arguments to functions in the same manner as scalars, vectors,
and matrices. In this case, we use the function pass_or_fail listed below.
message = pass_or_fail(ClassData(2));
message
File pass_or_fail.m