Data Containers
***************

Octave includes support for two different mechanisms to contain arbitrary data types in the same variable.  Structures, which are C-like, and are indexed with named fields, and cell arrays, where each element of the array can have a different data type and or shape.  Multiple input arguments and return values of functions are organized as another data container, the comma separated list.

Data Structures
===============

Octave includes support for organizing data in structures.  The current implementation uses an associative array with indices limited to strings, but the syntax is more like C-style structures.

Basic Usage and Examples
------------------------

Here are some examples of using data structures in Octave.

Elements of structures can be of any value type.  For example, the three expressions

     x.a = 1;
     x.b = [1, 2; 3, 4];
     x.c = "string";

create a structure with three elements.  The . character separates the structure name from the field name and indicates to Octave that this variable is a structure.  To print the value of the structure you can type its name, just as for any other variable:

     x
          => x =
             {
               a = 1
               b =

                 1  2
                 3  4

               c = string
             }

Note that Octave may print the elements in any order.

Structures may be copied just like any other variable:

     y = x
          => y =
             {
               a = 1
               b =

                 1  2
                 3  4

               c = string
             }

Since structures are themselves values, structure elements may reference other structures.  The following statements change the value of the element b of the structure x to be a data structure containing the single element d, which has a value of 3.

     x.b.d = 3;
     x.b
          => ans =
             {
               d = 3
             }

     x
          => x =
             {
               a = 1
               b =
               {
                 d = 3
               }

               c = string
             }

Note that when Octave prints the value of a structure that contains other structures, only a few levels are displayed.  For example:

     a.b.c.d.e = 1;
     a
          => a =
             {
               b =
               {
                 c =
                 {
                   1x1 struct array containing the fields:

                   d: 1x1 struct
                 }
               }
             }

This prevents long and confusing output from large deeply nested structures.  The number of levels to print for nested structures may be set with the function struct_levels_to_print, and the function print_struct_array_contents may be used to enable printing of the contents of structure arrays.

(struct_levels_to_print)

(print_struct_array_contents)

Functions can return structures.  For example, the following function separates the real and complex parts of a matrix and stores them in two elements of the same structure variable.

     function y = f (x)
       y.re = real (x);
       y.im = imag (x);
     endfunction

When called with a complex-valued argument, f returns the data structure containing the real and imaginary parts of the original function argument.

     f (rand (2) + rand (2) * I)
          => ans =
             {
               im =

                 0.26475  0.14828
                 0.18436  0.83669

               re =

                 0.040239  0.242160
                 0.238081  0.402523

             }

Function return lists can include structure elements, and they may be indexed like any other variable.  For example:

     [ x.u, x.s(2:3,2:3), x.v ] = svd ([1, 2; 3, 4]);
     x
          => x =
             {
               u =

                 -0.40455  -0.91451
                 -0.91451   0.40455

               s =

                  0.00000   0.00000   0.00000
                  0.00000   5.46499   0.00000
                  0.00000   0.00000   0.36597

               v =

                 -0.57605   0.81742
                 -0.81742  -0.57605

             }

It is also possible to cycle through all the elements of a structure in a loop, using a special form of the for statement (see Looping Over Structure Elements).

Structure Arrays
----------------

A structure array is a particular instance of a structure, where each of the fields of the structure is represented by a cell array.  Each of these cell arrays has the same dimensions.  Conceptually, a structure array can also be seen as an array of structures with identical fields.  An example of the creation of a structure array is

     x(1).a = "string1";
     x(2).a = "string2";
     x(1).b = 1;
     x(2).b = 2;

which creates a 2-by-1 structure array with two fields.  Another way to create a structure array is with the struct function (see Creating Structures).  As previously, to print the value of the structure array, you can type its name:

     x
          => x =
             {
               1x2 struct array containing the fields:

                 a
                 b
             }

Individual elements of the structure array can be returned by indexing the variable like X(1), which returns a structure with two fields:

     x(1)
          => ans =
             {
               a = string1
               b =  1
             }

Furthermore, the structure array can return a comma separated list of field values (see Comma Separated Lists), if indexed by one of its own field names.  For example:

     x.a
          =>
             ans = string1
             ans = string2

Here is another example, using this comma separated list on the left-hand side of an assignment:

     [x.a] = deal("new string1", "new string2");
      x(1).a
          => ans = new string1
      x(2).a
          => ans = new string2

Just as for numerical arrays, it is possible to use vectors as indices (see Index Expressions):

     x(3:4) = x(1:2);
     [x([1,3]).a] = deal("other string1", "other string2");
     x.a
          =>
             ans = other string1
             ans = new string2
             ans = other string2
             ans = new string2

The function size will return the size of the structure.  For the example above

     size(x)
          => ans =

               1   4

Elements can be deleted from a structure array in a similar manner to a numerical array, by assigning the elements to an empty matrix.  For example

     in = struct ("call1", {x, Inf, "last"},
                  "call2", {x, Inf, "first"})
          => in =
             {
               1x3 struct array containing the fields:

                 call1
                 call2
             }

     in(1) = [];
     in.call1
          =>
            ans = Inf
            ans = last

Creating Structures
-------------------

As well as indexing a structure with ".", Octave can create a structure with the struct command.  struct takes pairs of arguments, where the first argument in the pair is the fieldname to include in the structure and the second is a scalar or cell array, representing the values to include in the structure or structure array.  For example:

     struct ("field1", 1, "field2", 2)
     => ans =
           {
             field1 =  1
             field2 =  2
           }

If the values passed to struct are a mix of scalar and cell arrays, then the scalar arguments are expanded to create a structure array with a consistent dimension.  For example:

     s = struct ("field1", {1, "one"}, "field2", {2, "two"},
             "field3", 3);
     s.field1
          =>
             ans =  1
             ans = one

     s.field2
          =>
             ans =  2
             ans = two

     s.field3
          =>
             ans =  3
             ans =  3

If you want to create a struct which contains a cell array as an individual field, you have to put it into another cell array like in the following example:

     struct ("field1", {{1, "one"}}, "field2", 2)
          => ans =
             {
               field1 =

             {
               [1,1] =  1
               [1,2] = one
             }

               field2 =  2
             }

(struct)

The function isstruct can be used to test if an object is a structure or a structure array.

(isstruct)

Manipulating Structures
-----------------------

Other functions that can manipulate the fields of a structure are given below.

(nfields)

(fieldnames)

(isfield)

(getfield)

(setfield)

(rmfield)

(orderfields)

(substruct)

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.

(structfun)

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

(struct2cell)

Cell Arrays
===========

It can be both necessary and convenient to store several variables of different size or type in one variable.  A cell array is a container class able to do just that.  In general cell arrays work just like N-dimensional arrays with the exception of the use of { and } as allocation and indexing operators.

Basic Usage of Cell Arrays
--------------------------

As an example, the following code creates a cell array containing a string and a 2-by-2 random matrix

     c = {"a string", rand(2, 2)};

To access the elements of a cell array, it can be indexed with the { and } operators.  Thus, the variable created in the previous example can be indexed like this:

     c{1}
          => ans = a string

As with numerical arrays several elements of a cell array can be extracted by indexing with a vector of indexes

     c{1:2}
          => ans =

               (,
                 [1] = a string
                 [2] =

                    0.593993   0.627732
                    0.377037   0.033643

               ,)

The indexing operators can also be used to insert or overwrite elements of a cell array.  The following code inserts the scalar 3 on the third place of the previously created cell array

     c{3} = 3
          => c =

              {
                [1,1] = a string
                [1,2] =

                   0.593993   0.627732
                   0.377037   0.033643

                [1,3] =  3
              }

Details on indexing cell arrays are explained in Indexing Cell Arrays.

In general nested cell arrays are displayed hierarchically as in the previous example.  In some circumstances it makes sense to reference them by their index, and this can be performed by the celldisp function.

(celldisp)

To test if an object is a cell array, use the iscell function.  For example:

     iscell(c)
          => ans = 1

     iscell(3)
          => ans = 0

(iscell)

Creating Cell Array
-------------------

The introductory example (see Basic Usage of Cell Arrays) showed how to create a cell array containing currently available variables. In many situations, however, it is useful to create a cell array and then fill it with data.

The cell function returns a cell array of a given size, containing empty matrices.  This function is similar to the zeros function for creating new numerical arrays.  The following example creates a 2-by-2 cell array containing empty matrices

     c = cell(2,2)
          => c =

              {
                [1,1] = [](0x0)
                [2,1] = [](0x0)
                [1,2] = [](0x0)
                [2,2] = [](0x0)
              }

Just like numerical arrays, cell arrays can be multi-dimensional.  The cell function accepts any number of positive integers to describe the size of the returned cell array.  It is also possible to set the size of the cell array through a vector of positive integers.  In the following example two cell arrays of equal size are created, and the size of the first one is displayed

     c1 = cell(3, 4, 5);
     c2 = cell( [3, 4, 5] );
     size(c1)
          => ans =
              3   4   5

As can be seen, the size function also works for cell arrays.  As do other functions describing the size of an object, such as length, numel, rows, and columns.

(cell)

As an alternative to creating empty cell arrays, and then filling them, it is possible to convert numerical arrays into cell arrays using the num2cell, mat2cell and cellslices functions.

(num2cell)

(mat2cell)

(cellslices)

Indexing Cell Arrays
--------------------

As shown in see Basic Usage of Cell Arrays elements can be extracted from cell arrays using the { and } operators.  If you want to extract or access subarrays which are still cell arrays, you need to use the ( and ) operators.  The following example illustrates the difference:

     c = {"1", "2", "3"; "a", "b", "c"; "4", "5", "6"};
     c{2,3}
          => ans = c

     c(2,3)
          => ans =
             {
               [1,1] = c
             }

So with {} you access elements of a cell array, while with () you access a sub array of a cell array.

Using the ( and ) operators, indexing works for cell arrays like for multi-dimensional arrays.  As an example, all the rows of the first and third column of a cell array can be set to 0 with the following command:

     c(:, [1, 3]) = {0}
          =>  =
             {
               [1,1] = 0
               [2,1] = 0
               [3,1] = 0
               [1,2] = 2
               [2,2] =  10
               [3,2] =  20
               [1,3] = 0
               [2,3] = 0
               [3,3] = 0
             }

Note, that the above can also be achieved like this:

     c(:, [1, 3]) = 0;

Here, the scalar 0 is automatically promoted to cell array {0} and then assigned to the subarray of c.

To give another example for indexing cell arrays with (), you can exchange the first and the second row of a cell array as in the following command:

     c = {1, 2, 3; 4, 5, 6};
     c([1, 2], :) = c([2, 1], :)
          => =
             {
               [1,1] =  4
               [2,1] =  1
               [1,2] =  5
               [2,2] =  2
               [1,3] =  6
               [2,3] =  3
             }

Accessing multiple elements of a cell array with the { and } operators will result in a comma-separated list of all the requested elements (see Comma Separated Lists).  Using the { and } operators the first two rows in the above example can be swapped back like this:

     [c{[1,2], :}] = deal(c{[2, 1], :})
          => =
             {
               [1,1] =  1
               [2,1] =  4
               [1,2] =  2
               [2,2] =  5
               [1,3] =  3
               [2,3] =  6
             }

As for struct arrays and numerical arrays, the empty matrix [] can be used to delete elements from a cell array:

     x = {"1", "2"; "3", "4"};
     x(1, :) = []
          => x =
             {
               [1,1] = 3
               [1,2] = 4
             }

The following example shows how to just remove the contents of cell array elements but not delete the space for them:

     x = {"1", "2"; "3", "4"};
     x{1, :} = []
     => x =
           {
             [1,1] = [](0x0)
             [2,1] = 3
             [1,2] = [](0x0)
             [2,2] = 4
           }

Cell Arrays of Strings
----------------------

One common use of cell arrays is to store multiple strings in the same variable.  It is also possible to store multiple strings in a character matrix by letting each row be a string.  This, however, introduces the problem that all strings must be of equal length. Therefore, it is recommended to use cell arrays to store multiple strings.  For cases, where the character matrix representation is required for an operation, there are several functions that convert a cell array of strings to a character array and back.  char and strvcat convert cell arrays to a character array (see Concatenating Strings), while the function cellstr converts a character array to a cell array of strings:

     a = ["hello"; "world"];
     c = cellstr (a)
          => c =
              {
                [1,1] = hello
                [2,1] = world
              }

(cellstr)

One further advantage of using cell arrays to store multiple strings is that most functions for string manipulations included with Octave support this representation.  As an example, it is possible to compare one string with many others using the strcmp function.  If one of the arguments to this function is a string and the other is a cell array of strings, each element of the cell array will be compared to the string argument:

     c = {"hello", "world"};
     strcmp ("hello", c)
          => ans =
             1   0

The following string functions support cell arrays of strings: char, strvcat, strcat (see Concatenating Strings), strcmp, strncmp, strcmpi, strncmpi (see Comparing Strings), str2double, deblank, strtrim, strtrunc, strfind, strmatch, , regexp, regexpi (see Manipulating Strings) and str2double (see String Conversions).

The function iscellstr can be used to test if an object is a cell array of strings.

(iscellstr)

Processing Data in Cell Arrays
------------------------------

Data that is stored in a cell array can be processed in several ways depending on the actual data.  The simplest way to process that data is to iterate through it using one or more for loops.  The same idea can be implemented more easily through the use of the cellfun function that calls a user-specified function on all elements of a cell array.

(cellfun)

An alternative is to convert the data to a different container, such as a matrix or a data structure.  Depending on the data this is possible using the cell2mat and cell2struct functions.

(cell2mat)

(cell2struct)

Comma Separated Lists
=====================

Comma separated lists  (Comma-separated lists are also sometimes informally referred to as cs-lists.) are the basic argument type to all Octave functions - both for input and return arguments.  In the example

     max (A, B)

A, B is a comma separated list.  Comma separated lists can appear on both the right and left hand side of an assignment.  For example

     x = [1 0 1 0 0 1 1; 0 0 0 0 0 0 7];
     [I, J] = find (X, 2, "last");

Here, X, 2, "last" is a comma separated list constituting the input arguments of find.  find returns a comma separated list of output arguments which is assigned element by element to the comma separated list I, J.

Another example of where comma separated lists are used is in the creation of a new array with [] (see Matrices) or the creation of a cell array with {} (see Basic Usage of Cell Arrays).  In the expressions

     a = [1, 2, 3, 4];
     c = {4, 5, 6, 7};

both 1, 2, 3, 4 and 4, 5, 6, 7 are comma separated lists.

Comma separated lists cannot be directly manipulated by the user.  However, both structure arrays and cell arrays can be converted into comma separated lists, and thus used in place of explicitly written comma separated lists.  This feature is useful in many ways, as will be shown in the following subsections.

Comma Separated Lists Generated from Cell Arrays
------------------------------------------------

As has been mentioned above (see Indexing Cell Arrays), elements of a cell array can be extracted into a comma separated list with the { and } operators.  By surrounding this list with [ and ], it can be concatenated into an array.  For example:

     a = {1, [2, 3], 4, 5, 6};
     b = [a{1:4}]
          => b =
              1   2   3   4

Similarly, it is possible to create a new cell array containing cell elements selected with {}.  By surrounding the list with { and } a new cell array will be created, as the following example illustrates:

     a = {1, rand(2, 2), "three"};
     b = { a{ [1, 3] } }
          => b =
              {
                [1,1] =  1
                [1,2] = three
              }

Furthermore, cell elements (accessed by {}) can be passed directly to a function.  The list of elements from the cell array will be passed as an argument list to a given function as if it is called with the elements as individual arguments.  The two calls to printf in the following example are identical but the latter is simpler and can handle cell arrays of an arbitrary size:

     c = {"GNU", "Octave", "is", "Free", "Software"};
     printf ("%s ", c{1}, c{2}, c{3}, c{4}, c{5});
          -| GNU Octave is Free Software
     printf ("%s ", c{:});
          -| GNU Octave is Free Software

If used on the left-hand side of an assignment, a comma separated list generated with {} can be assigned to.  An example is

     in{1} = [10, 20, 30, 40, 50, 60, 70, 80, 90];
     in{2} = inf;
     in{3} = "last";
     in{4} = "first";
     out = cell (4, 1);
     [out{1:3}] = find (in{1 : 3});
     [out{4:6}] = find (in{[1, 2, 4]})
          => out =
             {
               [1,1] = 1
               [2,1] = 9
               [3,1] = 90
               [4,1] = 1
               [3,1] = 1
               [4,1] = 10
             }

Comma Separated Lists Generated from Structure Arrays
-----------------------------------------------------

Structure arrays can equally be used to create comma separated lists.  This is done by addressing one of the fields of a structure array.  For example:

     x = ceil (randn (10, 1));
     in = struct ("call1", {x, 3, "last"},
                  "call2", {x, inf, "first"});
     out = struct ("call1", cell (2, 1), "call2", cell (2, 1));
     [out.call1] = find (in.call1);
     [out.call2] = find (in.call2);