[MATLAB logo] Exploiting MATLAB's Data Structures

Solution #6 - Structures & Comma-Separated Lists

Structures are arrays with named fields. The elements in each field don't have to be commersurate. In fact it makes sense to think of structures as cell arrays with a special indexing syntax for one of the dimensions (the functions cell2struct and struct2cell make this conversion explicit). If you have more than one structure element, the structure array is kind of like a database with each element a record. To create structure arrays use the .name notation. For instance,
db.name = 'Clay'
db.height = 182
creates a 1-by-1 structure array with two fields. We can add elements to the structure via indexing
db(2).name = 'Loren'
at this point the db(2).height is empty since we haven't defined it yet. All undefined structure fields are initialized to empty. If you access more than one element of the structure at a time you produce a comma-separate list. Perhaps the most surprising is an expression like
db.name
when the structure array has more than one element. In this case, we end up with the comma-separated list
db(1).name,db(2).name
This can be used with the cell array constructor syntax to create a cell array of strings
{db.name}
Goal: Create and manipulate a structure array.

Key concepts: structures, structure fields, comma-separated lists

Key functions: struct, mean, length

Solution

  1. Create a "database", db, with the names and heights in cms of 3 of your classmates. Use the fields 'name', and 'height'
  2. db.name = 'Clay';db.height = 182;db(2).name = 'Loren';db(2).height = 120;db(3).name = 'Jack';db(3).height = 165;
    or
    db = struct('name',{'Clay','Loren','Jack'},'height',{182 120 165});
  3. Find your group's average height. Use comma-separate list syntax if possible. Is this operation vectorizable?
  4. avg = mean([db.height]);
    It is vectorizable.
  5. Find the mean length of your group's names. Is this operation vectorizable?
  6. for i=1:length(db)len(i) = length(db(i).name);endm = mean(len);
    It is vectorizable. Here's the alternate solution
    str = char(db.name);m = length(find(isspace(str)==0))/size(str,1)

Copyright © 1997 The MathWorks, Inc.
clay@mathworks.com
$Revision$ $Date$