Programming

Replacing Lists of Variables with Cell Arrays

Cell arrays can replace comma-separated lists of MATLAB variables in

• Function input lists
• Function output lists
• Display operations
• Array constructions (square brackets and curly braces)

If you use the colon to index multiple cells in conjunction with the curly brace notation, MATLAB treats the contents of each cell as a separate variable. For example, assume you have a cell array `T` where each cell contains a separate vector. The expression `T{1:5}` is equivalent to a comma-separated list of the vectors in the first five cells of `T`.

Consider the cell array `C`:

• ```C(1) = {[1 2 3]};
C(2) = {[1 0 1]};
C(3) = {1:10};
C(4) = {[9 8 7]};
C(5) = {3};
```

To convolve the vectors in `C(1)` and `C(2)` using `conv`,

• ```d = conv(C{1:2})
d =
1     2     4     2     3
```

Display vectors two, three, and four with

• ```C{2:4}
ans =
1   0   1

ans =
1   2   3   4   5   6   7   8   9   10

ans =
9   8   7
```

Similarly, you can create a new numeric array using the statement

• ```B = [C{1}; C{2}; C{4}]
B =
1   2   3
1   0   1
9   8   7
```

You can also use content indexing on the left side of an assignment to create a new cell array where each cell represents a separate output argument:

• ```[D{1:2}] = eig(B)
D =
[3x3 double]    [3x3 double]
```

You can display the actual eigenvectors and eigenvalues using `D{1}` and `D{2}`.

 Note    The `varargin` and `varargout` arguments allow you to specify variable numbers of input and output arguments for MATLAB functions that you create. Both `varargin` and `varargout` are cell arrays, allowing them to hold various sizes and kinds of MATLAB data. See Passing Variable Numbers of Arguments for details.

 Deleting Cells Applying Functions and Operators