Next: Cell Arrays of Strings, Previous: Creating Cell Arrays, Up: Cell Arrays
As shown in the introductory example elements can be inserted from cell
arrays using the `{' and `}' operators. Besides the change
of operators, indexing works for cell arrays like for multidimensional
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 code
c{:, [1, 3]} = 0;
Accessing values in a cell array is, however, different from the same operation for numerical arrays. Accessing a single element of a cell array is very similar to numerical arrays, for example
element = c{1, 2};
This will, however, not work when accessing multiple elements of a cell array, because it might not be possible to represent all elements with a single variable as is the case with numerical arrays.
Accessing multiple elements of a cell array with the `{' and
`}' operators will result in a comma-separated list of all
the requested elements. This list can then be used anywhere where a
comma-separated list is used, such as in the creation of a new
numerical array or cell array, or be passed as arguments to a
function. If all the accessed elements of a cell array are scalars or
column vectors, they can be concatenated into a new column vector
containing the elements, by surrounding the list with [
and
]
as in the following example
a = {1, [2, 3], 4}; b = [a{:}] => b = 1 2 3 4
It is also possible to pass the accessed elements 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
arguments. The two calls to printf
in the following example are
identical but the latter is more simple and handles more situations
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
Just like it is possible to create a numerical array from selected elements of a cell array, it is possible to create a new cell array containing the selected elements. By surrounding the list with `{' and `}' a new cell array will be created, like the following example illustrates
a = {1, rand(2, 2), "three"}; b = { a{ [1, 3] } } => b = { [1,1] = 1 [1,2] = three }
This syntax is however a bit cumbersome, and since this is a common operation, it is possible to achieve the same using the `(' and `)' operators for indexing. When a cell array is indexed using the `(' and `)' operators a new cell array containing the selected elements. Using this syntax, the previous example can be simplified into the following
a = {1, rand(2, 2), "three"}; b = a( [1, 3] ) => b = { [1,1] = 1 [1,2] = three }