Chuyển đến nội dung

Bài 15 · Data Types and Text

Structures

Learn MATLAB and Octave structures: named fields, dynamic field names, struct arrays, arrayfun, nested structs, isfield and rmfield, with Python stand-ins.

A cell array stores mixed data by position: "the second item". That works for a few values, but it quickly becomes unreadable. What does person{3} mean? A structure (usually called a struct) fixes this by giving every piece of data a name. A struct is a bundle of fields, and each field can hold any type, just like a cell can.

Structs are how MATLAB and Octave programs represent records: a measurement with a timestamp and a value, a customer with a name and a list of orders, a settings object passed to a function. Many toolbox functions return structs, and optimset-style option bundles are structs too.

Code marked matlab is read-only on this site. The runnable examples are Python stand-ins (mostly dictionaries) that mirror the MATLAB behavior and point out where they differ.

A struct is a named bundle

Fields Each value has a name.
Any type Numbers, text, matrices, cells, structs.
Dot access person.name reads the field.
1 / 2

Creating a struct

The simplest way is to assign to a field with a dot. The struct is created the first time you do it:

MATLAB
person.name = 'Ada';
person.age = 36;
person.scores = [90 85 77];
person
% person =
%   scalar structure containing the fields:
%     name = Ada
%     age = 36
%     scores = ...

The struct function builds one in a single call from name and value pairs:

MATLAB
p = struct('name', 'Grace', 'age', 45);
p.age = p.age + 1;      % update a field
p.age                   % 46
fieldnames(p)           % {'name'; 'age'}

Read a field with the dot, and use normal indexing on its value: person.scores(2) is 85. Field names follow variable naming rules: letters, digits and underscores, starting with a letter.

When you pass a cell array as a value to struct, MATLAB builds a struct array with one element per cell. To store a cell array inside a single field, wrap it in another cell: struct('tags', {{'a', 'b'}}).

Python A record as a dictionary

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A Python dictionary plays the role of the struct. The big difference is the syntax: person.name in MATLAB versus person["name"] here, and MATLAB's 1-based scores(2) becomes [1] in Python.

Dynamic field names

Sometimes the field name is stored in a variable, for example when you loop over column headings. Put the name in parentheses after the dot:

MATLAB
s = struct();
keys = {'alpha', 'beta', 'gamma'};
for k = 1:numel(keys)
    s.(keys{k}) = k * 10;
end
s.beta            % 20
name = 'gamma';
s.(name)          % 30

s.(name) means "the field whose name is the contents of name". Without the parentheses, s.name would look for a field literally called name. Because the name is just text, you can also build it: s.(['run_' num2str(3)]) = 1 creates a field called run_3.

Testing, removing and listing fields

Three functions help you manage fields at run time:

MATLAB
isfield(s, 'beta')              % 1
isfield(s, {'beta', 'zeta'})    % [1 0]   (one answer per name)
s = rmfield(s, 'alpha');        % returns a copy without that field
fieldnames(s)                   % {'beta'; 'gamma'}
numfields(s)                    % 2     (MATLAB; Octave also has numfields)

rmfield returns a new struct; it does not change s in place, so you must assign the result. Reading a field that does not exist is an error, so check with isfield first when the field is optional.

Python Dynamic fields and checks

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python's dictionary indexing is already dynamic, so there is no special syntax; the stand-in just makes the idea visible.

Struct arrays

When you have many records with the same fields, use a struct array, a list of structs. Index it with parentheses and read fields with a dot:

MATLAB
students(1).name = 'Ada';   students(1).score = 91;
students(2).name = 'Grace'; students(2).score = 84;
students(3).name = 'Kat';   students(3).score = 97;

size(students)              % 1 3
students(2).name            % 'Grace'
scores = [students.score]   % [91 84 97]
names  = {students.name}    % {'Ada', 'Grace', 'Kat'}

Writing students.score without an index produces a comma-separated list of every element's field, the same trick you saw with cells. Wrap it in [ ] to join numbers or in { } to keep text as a cell. To filter, combine this with logical indexing:

MATLAB
top = students([students.score] > 90);
numel(top)                  % 2

To run a function over each element, use arrayfun with 'UniformOutput', false when the results are not scalars:

MATLAB
labels = arrayfun(@(s) sprintf('%s: %d', s.name, s.score), students, ...
                  'UniformOutput', false)
% {'Ada: 91', 'Grace: 84', 'Kat: 97'}
Python Struct array as a list of dicts

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A list of dictionaries is the closest Python match. The list comprehensions replace [students.score] and arrayfun.

Nested structs

A field can hold another struct, which lets you describe layered data:

MATLAB
cfg.window.width = 800;
cfg.window.height = 600;
cfg.title = 'Demo';
cfg.window.width      % 800
area = cfg.window.width * cfg.window.height   % 480000

Each dot goes one level deeper. MATLAB creates the intermediate structs on assignment, so you never have to declare cfg.window first. Display shows nested structs collapsed past a certain depth, and disp(cfg.window) prints the inner one.

Structs versus cells versus dictionaries

Use a struct when you know the parts by name. Use a cell array when the position is what matters or the count is unknown. Use a containers.Map (see Tables and Maps) when the keys are arbitrary text only known at run time, such as words in a text. A struct array is a good fit for tabular records of modest size; for large tables, MATLAB's table type is more convenient.

Struct arrays whose elements hold the same number and type of fields are efficient. Building one by appending in a loop is slow for large counts, so preallocate with repmat(struct('name', '', 'score', 0), 1, n) first.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Given s.alpha = 1, what does name = 'alpha'; s.(name) return?

    Parentheses after the dot make MATLAB use the contents of the variable as the field name, so s.(name) reads s.alpha.
  2. 2. What does [students.score] produce when students is a struct array?

    students.score expands into a comma-separated list, and the square brackets concatenate the values into one numeric array.
  3. 3. Why must you write s = rmfield(s, 'x') instead of rmfield(s, 'x')?

    MATLAB functions work on copies. rmfield returns a new struct without the field, so assign it back to keep the change.
  4. 4. Which is the best fit for storing a record with the parts name, age and scores?

    A struct gives each part its own name and lets the fields have different types, which a matrix cannot do.

Summary

  • A struct bundles named fields of any type; create it with s.field = value or struct('name', value, ...).
  • Use s.(name) for dynamic field names, and isfield, rmfield and fieldnames to inspect and change fields.
  • A struct array holds many records with the same fields; [arr.field] and {arr.field} gather values.
  • arrayfun applies a function to each element of a struct array; use 'UniformOutput', false for non-scalar results.
  • Structs can nest, and a Python dictionary (or a list of dictionaries) is a good mental model.

Next: Tables and Maps, for column-oriented data and key-value lookups.

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.