Presentation on theme: "CMPS 1371 Introduction to Computing for Engineers STRUCTURE ARRAYS."— Presentation transcript:
CMPS 1371 Introduction to Computing for Engineers STRUCTURE ARRAYS
Structure Arrays Similar to Cell Arrays Multiple arrays of differing data types can be stored in structure arrays Instead of using content indexing each of the matrices is given a location called a field
Structures This class of arrays allows you to store dissimilar arrays together. The elements in the structure are accessed using named fields You create a structure array either by using assignment statements or by using the struct function. Structure arrays use the dot notation (.) to specify and to access the fields.
Structures Think about a student database (e.g. name, social security number, email address, test scores). There are four fields (4 field names): 3 string and 1 vector containing numerical elements. A structure consists of all this information for a single student and a structure array is an array of such structures for different students. name ssn email test scores Student record
Arrangement of data in the structure array student.
Entering Data We can enter the data directly >> student.name = 'John Smith'; >> student.ssn = '123-45-6789'; >> student.email = 'email@example.com'; >> student.tests = [67,75,84];
Entering Data We can also enter the data through a structure function “struct”: >> student = struct(‘name’, ‘John Smith’, ‘ssn’, ‘123-45-6789’, ‘email’, ’firstname.lastname@example.org’, ‘tests’, [67,75,84])
Access Data The name student is now used to refer to the entire array of structures. We can access elements of a structure array as if it was a normal array For example: >> student(1)
Functions The Matlab function fieldnames recovers all the field names associated with a structure. returns a cell array of strings. For example: >> fieldnames(student) ans = 'name' 'ssn' 'email' 'tests‘ Matlab function rmfield - removes fields from a structure.
Arrays of structures Often we will want multiple instances of a single structure. We can build up an array of structures. We call this array a structure array. Matlab allows a structure array to grow automatically.
Add another student >>student(2).name = ‘Mary Jones’; Since we only specified the name field of student(2), Matlab initializes the remaining fields to empty arrays: We can then fill in extra details as required. >>student(2).ssn = ‘431-56-9832’; >>student(2).email = ‘email@example.com’ >>student(2).tests = [84, 78, 93];
Why are structures so much better Structures use the "name" of a "field" to access the data…so the name can be useful things like 'artist'. Compared to "3 rd element" Structures can be thought of as a "data structure" –organizes the data in a logical way that can be applied many times. Structures can be put into arrays as long as the structures all have the same fields. This makes having many "objects" of the same type easy.