A Student Database Matlab Help

A Student Database

Create a structure array to contain the following types of student data:
• Student name.
• Social Security number.
:. Email address.
• Test scores.
Enter the data shown in Figure 2.7-1 into the database

Solution

You can create the structure array by typing the following either in the interactive mode or in a script file. Start with the data for the first student

student name = ‘John Smith’;
student. SSN = ‘392-77-1786’;
student email = smithj@myschool.edu.;
student tests = [67,75,84);

If you then type
»student
at the command line, you will see the following response:
name: ‘John Smith’
SSN: = ‘392-77-1786’
email: ‘smithj@myschool.edu’
tests: = [67 75 84)

To determine the size of the array, type size (student). The result is ans = 1 1,
which indicates that it is a 1 x 1 structure array.
To add a second student to the database, use a subscript 2 enclosed in parentheses
after the structure array’s name and enter the new information. For example,
type
student (2) name = Mary Jones’;
student 2) SSN =  S92
student 2) emai = jonesm@myscnool.edu’;
student (2) tests = [84,78,93);
This process “expands” the array. Before we entered the data for the second student, dimension of the structure array was I x I (it was a single structure). Now it is 1 x 2 array consisting of two structures, arranged in one row and two columns. You confirm this information by typing size (student), which returns ans = 1 2.
~you now type length (student) ,you will get the result ans = 2, which indis that the array has two elements (two structures). When a structure array has more one structure, MATLAB does not display the individual field contents when you the structure array’s name. For example, if you now type student, MATLAB
displays .

>student  =
struct array with fields

name
SSN
email
tests

Structure functions

Structure functions

You can also obtain information about the fields by using the fieldnames function
(see Table 2.7-1). For example:
»fieldnames(student)
ans =
‘name’
‘SSN’
’email’
‘tests’
As you.fill in more student information, MATLAB assigns the same number of fields and the same field names to each element. If you do not enter some information-for example, suppose you do not know someone’s email address-MATLAB assigns an empty matrix to that field for that student. The fields, can have different sizes. For example, each name field can contain a different number of characters, and the arrays containing the test scores can be different sizes, as would be the case if a certain student did not take the second test.

Posted on July 15, 2015 in Numeric Cell And Structure Arrays

Share the Story

Back to Top
Share This