6.1.5 Processing Data in Structures

The simplest way to process data in a structure is within a for loop (see Looping Over Structure Elements). A similar effect can be achieved with the structfun function, where a user defined function is applied to each field of the structure. See structfun.

Alternatively, to process the data in a structure, the structure might be converted to another type of container before being treated.

: c = struct2cell (s)

Create a new cell array from the objects stored in the struct object.

If f is the number of fields in the structure, the resulting cell array will have a dimension vector corresponding to [f size(s)]. For example:

s = struct ("name", {"Peter", "Hannah", "Robert"},
           "age", {23, 16, 3});
c = struct2cell (s)
   ⇒ c = {2x1x3 Cell Array}
c(1,1,:)(:)
   ⇒
      {
        [1,1] = Peter
        [2,1] = Hannah
        [3,1] = Robert
      }
c(2,1,:)(:)
   ⇒
      {
        [1,1] = 23
        [2,1] = 16
        [3,1] = 3
      }

See also: cell2struct, namedargs2cell, fieldnames.

: c = namedargs2cell (s)

Create a cell array of field name/value pairs from a scalar structure.

Example:

s.Name = "Peter";
s.Height = 185;
s.Age = 42;

c = namedargs2cell (s)
  ⇒ { "Name", "Peter", "Height", 185, "Age", 42 }

See also: struct2cell.

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v6.3.0/Processing-Data-in-Structures.html