23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Structures<br />

For example, for the 1-by-3 structure array patient, size(patient) returns<br />

the vector [1 3]. Thestatement size(patient(1,2).name) returns the<br />

length of the name string for element (1,2) of patient.<br />

Adding Fields to Structures<br />

You can add a field to every structure inanarraybyaddingthefieldtoa<br />

single structure. For example, to add a social security number field to the<br />

patient array, use an assignment like<br />

patient(2).ssn = '000-00-0000';<br />

Now patient(2).ssn has the assigned value. Every other structure in the<br />

array also has the ssn field, but these fields contain the empty matrix until<br />

you explicitly assign a value to them.<br />

See “Naming conventions for Structure Field Names” on page 2-78 for<br />

guidelines to creating valid field names.<br />

Adding or Modifying Fields With the setfield Function<br />

The setfield function offers another way to add or modify fields of a<br />

structure. Given the structure<br />

mystr(1,1).name = 'alice';<br />

mystr(1,1).ID = 0;<br />

mystr(2,1).name = 'gertrude';<br />

mystr(2,1).ID = 1;<br />

You can change the name field of mystr(2,1) using<br />

mystr = setfield(mystr, {2,1}, 'name', 'ted');<br />

mystr(2,1).name<br />

ans =<br />

ted<br />

Adding New Fields Dynamically<br />

To add new fields to a structure, specifying the names for these fields at<br />

run-time, see the section on “Using Dynamic Field Names” on page 2-81.<br />

2-83

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!