TExcelTAD
Home › MATLAB / Octave › Structures

Structures

A structure (struct) groups related data under field names, like a record in a database or an object without methods. Instead of remembering that info{2} is the year, you write person.born.

Creating a structure

The simplest way is to assign to fields with dot notation; the structure is created on the fly:

matlab · try it yourself
car.make = 'Volvo';
car.year = 2019;
car.mileage = [12000 25400 38100];
car
fprintf('%s from %d, %d km so far\n', car.make, car.year, car.mileage(end));
car =

  scalar structure containing the fields:

    make = Volvo
    year = 2019
    mileage =

       12000   25400   38100


Volvo from 2019, 38100 km so far

Fields can hold any value: numbers, text, arrays, cell arrays and other structures. Alternatively, build it in one call with struct(name, value, ...):

matlab · try it yourself
p = struct('name', 'Sensor A', 'unit', 'degC', 'limits', [-40 85]);
fprintf('%s measures in %s, range %d to %d\n', p.name, p.unit, p.limits(1), p.limits(2));
Sensor A measures in degC, range -40 to 85

Note: If a value passed to struct is a cell array, struct creates a struct array with one element per cell. To store a cell array in a single field, wrap it in another pair of braces: struct('tags', {{'a', 'b'}}).

Working with fields

Function Purpose
fieldnames(s) Cell array of field names
isfield(s, 'f') Does the field exist?
rmfield(s, 'f') Copy of s without that field
s.(name) Dynamic field: the field whose name is in variable name
orderfields(s) Copy with fields sorted alphabetically
matlab · try it yourself
s = struct('width', 4, 'height', 3);
disp(fieldnames(s)')
disp(isfield(s, 'depth'))
s.depth = 2;
f = 'height';
s.(f) = s.(f) * 10;        % dynamic field name
names = fieldnames(s);
for k = 1:numel(names)
    fprintf('%s = %g\n', names{k}, s.(names{k}));
end
s = rmfield(s, 'depth');
disp(numel(fieldnames(s)))
{
  [1,1] = width
  [1,2] = height
}
0
width = 4
height = 30
depth = 2
2

Dynamic field names, s.(name), let you loop over fields or build field names from data.

Nested structures

A field can contain another structure, giving a tree of data:

matlab · try it yourself
config.window.width = 800;
config.window.height = 600;
config.colors.background = [1 1 1];
config.colors.text = [0 0 0];
config.title = 'Viewer';
fprintf('%s: %dx%d\n', config.title, config.window.width, config.window.height);
disp(fieldnames(config)')
Viewer: 800x600
{
  [1,1] = window
  [1,2] = colors
  [1,3] = title
}

Structure arrays

Several structures with the same fields form a struct array, indexed with parentheses. This is a natural way to store a list of records:

matlab · try it yourself
students(1).name = 'Lina';  students(1).score = 88;
students(2).name = 'Omar';  students(2).score = 74;
students(3).name = 'Zoe';   students(3).score = 93;
disp(size(students))
fprintf('%s: %d\n', students(2).name, students(2).score);

scores = [students.score]            % collect a field from every element
[~, best] = max(scores);
fprintf('Top student: %s\n', students(best).name);
names = {students.name};
fprintf('All: %s\n', strjoin(names, ', '));
   1   3
Omar: 74
scores =

   88   74   93

Top student: Zoe
All: Lina, Omar, Zoe

students.score produces a comma-separated list of the field from every element: wrap it in [] for numbers or {} for text.

Struct vs cell array

Structure Cell array
Access by Field name s.name Position c{3}
Best for Records with named parts Lists of items
Self-documenting Yes No
Example One patient's data A list of file names

They combine well: a struct array of records, or a struct field holding a cell array of tags.

Test yourself

How do you read the field whose name is stored in the variable f?

  1. s.f
  2. s(f)
  3. s.(f)
  4. s{f}

For a struct array p with a numeric field age, what does [p.age] give?

  1. The first age
  2. A row vector of all ages
  3. A cell array of ages
  4. An error

Which function tells you whether a structure has a field called 'id'?

  1. exist(s, 'id')
  2. isfield(s, 'id')
  3. hasfield(s, 'id')
  4. fieldnames(s, 'id')