Main Content

Comma-Separated Lists

What Is a Comma-Separated List?

When you type in a series of numbers separated by commas, MATLAB® creates a comma-separated list and returns each value individually.

1,2,3
ans =

     1


ans =

     2


ans =

     3

When used with large and more complex data structures like MATLAB structures and cell arrays, comma-separated lists can help simplify your code.

Generating a Comma-Separated List

You can generate a comma-separated list from either a cell array or a MATLAB structure.

Generating a List from a Cell Array

When you extract multiple elements from a cell array, the result is a comma-separated list. Define a 4-by-6 cell array.

C = cell(4,6);
for k = 1:24
    C{k} = k*2;
end
C
C =

  4×6 cell array

    {[2]}    {[10]}    {[18]}    {[26]}    {[34]}    {[42]}
    {[4]}    {[12]}    {[20]}    {[28]}    {[36]}    {[44]}
    {[6]}    {[14]}    {[22]}    {[30]}    {[38]}    {[46]}
    {[8]}    {[16]}    {[24]}    {[32]}    {[40]}    {[48]}

Extract the fifth column to generate a comma-separated list.

C{:,5}
ans =

    34


ans =

    36


ans =

    38


ans =

    40

This is the same as explicitly typing the list.

C{1,5},C{2,5},C{3,5},C{4,5}

Generating a List from a Structure

When you extract a field of a structure array across one of its dimensions, the result is a comma-separated list.

Start by converting the cell array used above into a 4-by-1 MATLAB structure with six fields: f1 through f6. Read field f5 for all rows, and MATLAB returns a comma-separated list.

S = cell2struct(C,{'f1','f2','f3','f4','f5','f6'},2);
S.f5
ans =

    34


ans =

    36


ans =

    38


ans =

    40

This is the same as explicitly typing the list.

S(1).f5,S(2).f5,S(3).f5,S(4).f5

Assigning Output from a Comma-Separated List

You can assign any or all consecutive elements of a comma-separated list to variables with a simple assignment statement. Define the cell array Cand assign the first row to variables c1 through c6.

C = cell(4,6);
for k = 1:24
    C{k} = k*2;
end
[c1,c2,c3,c4,c5,c6] = C{1,1:6};
c5
c5 =

    34
When you specify fewer output variables than the number of outputs returned by the expression, MATLAB assigns the first N outputs to those N variables and ignores any remaining outputs. In this example, MATLAB assigns C{1,1:3} to the variables c1, c2, and c3 and ignores C{1,4:6}.
[c1,c2,c3] = C{1,1:6};
You can assign structure outputs in the same manner.
S = cell2struct(C,{'f1','f2','f3','f4','f5','f6'},2);
[sf1,sf2,sf3] = S.f5;
sf3
sf3 =

    38
You also can use the deal function for this purpose.

Assigning to a Comma-Separated List

The simplest way to assign multiple values to a comma-separated list is to use the deal function. This function distributes its input arguments to the elements of a comma-separated list.

This example uses deal to overwrite each element in a comma-separated list. First initialize a two-element list. This step is necessary because you cannot use comma-separated list assignment with an undefined variable when using : as an index. See Comma-Separated List Assignment to an Undefined Variable for more information.

c{1} = []; 
c{2} = [];
c{:}
ans =

     []


ans =

     []

Use deal to overwrite each element in the list.

[c{:}] = deal([10 20],[14 12]);
c{:}
ans =

    10    20


ans =

    14    12

This example works in the same way, but with a comma-separated list of vectors in a structure field.

s(1).field1 = [[]];
s(2).field1 = [[]];
s.field1
ans =

     []


ans =

     []

Use deal to overwrite the structure fields.

[s.field1] = deal([10 20],[14 12]);
s.field1
ans =

    10    20


ans =

    14    12

How to Use Comma-Separated Lists

Common uses for comma-separated lists are:

These sections provide examples of using comma-separated lists with cell arrays. Each of these examples applies to structures as well.

Constructing Arrays

You can use a comma-separated list to enter a series of elements when constructing a matrix or array. When you specify a list of elements with C{:,5}, MATLAB inserts the four individual elements.

C = cell(4,6);
for k = 1:24
    C{k} = k*2;
end
A = {'Hello',C{:,5},magic(4)}
A =

  1×6 cell array

    {'Hello'}    {[34]}    {[36]}    {[38]}    {[40]}    {4×4 double}

When you specify the C cell itself, MATLAB inserts the entire cell array.

A = {'Hello',C,magic(4)}
A =

  1×3 cell array

    {'Hello'}    {4×6 cell}    {4×4 double}

Displaying Arrays

Use a list to display all or part of a structure or cell array.

A{:}
ans =

    'Hello'


ans =

  4×6 cell array

    {[2]}    {[10]}    {[18]}    {[26]}    {[34]}    {[42]}
    {[4]}    {[12]}    {[20]}    {[28]}    {[36]}    {[44]}
    {[6]}    {[14]}    {[22]}    {[30]}    {[38]}    {[46]}
    {[8]}    {[16]}    {[24]}    {[32]}    {[40]}    {[48]}


ans =

    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

Concatenation

Putting a comma-separated list inside square brackets extracts the specified elements from the list and concatenates them.

A = [C{:,5:6}]
A =

    34    36    38    40    42    44    46    48

Function Call Arguments

When writing the code for a function call, you enter the input arguments as a list with each argument separated by a comma. If you have these arguments stored in a structure or cell array, then you can generate all or part of the argument list from the structure or cell array instead. This can be especially useful when passing in variable numbers of arguments.

This example passes several name-value arguments to the plot function.

X = -pi:pi/10:pi;
Y = tan(sin(X)) - sin(tan(X));
C = cell(2,3);
C{1,1} = 'LineWidth';
C{2,1} = 2;
C{1,2} = 'MarkerEdgeColor';
C{2,2} = 'k';
C{1,3} = 'MarkerFaceColor';
C{2,3} = 'g';
figure
plot(X,Y,'--rs',C{:})

Function Return Values

MATLAB functions can also return more than one value to the caller. These values are returned in a list with each value separated by a comma. Instead of listing each return value, you can use a comma-separated list with a structure or cell array. This becomes more useful for functions that have variable numbers of return values.

This example returns three values to a cell array.

C = cell(1,3);
[C{:}] = fileparts('work/mytests/strArrays.mat')
C =

  1×3 cell array

    {'work/mytests'}    {'strArrays'}    {'.mat'}

Fast Fourier Transform Example

The fftshift function swaps the left and right halves of each dimension of an array. For the vector [0 2 4 6 8 10], the output is [6 8 10 0 2 4]. For a multidimensional array, fftshift performs this swap along each dimension.

fftshift uses vectors of indices to perform the swap. For the vector shown above, the index [1 2 3 4 5 6] is rearranged to form a new index [4 5 6 1 2 3]. The function then uses this index vector to reposition the elements. For a multidimensional array, fftshift constructs an index vector for each dimension. A comma-separated list makes this task much simpler.

Here is the fftshift function.

function y = fftshift(x)
    numDims = ndims(x);
    idx = cell(1,numDims);
    for k = 1:numDims
        m = size(x,k);
        p = ceil(m/2);
        idx{k} = [p+1:m 1:p];
    end
    y = x(idx{:});
end

The function stores the index vectors in cell array idx. Building this cell array is relatively simple. For each of the N dimensions, determine the size of that dimension and find the integer index nearest the midpoint. Then, construct a vector that swaps the two halves of that dimension.

By using a cell array to store the index vectors and a comma-separated list for the indexing operation, fftshift shifts arrays of any dimension using just a single operation: y = x(idx{:}). If you use explicit indexing, you need to write one if statement for each dimension you want the function to handle.

    if ndims(x) == 1
        y = x(index1);
    else if ndims(x) == 2
        y = x(index1,index2);
        end
    end

Another way to handle this without a comma-separated list is to loop over each dimension, converting one dimension at a time and moving data each time. With a comma-separated list, you move the data just once. A comma-separated list makes it easy to generalize the swapping operation to any number of dimensions.

Troubleshooting Operations with Comma-Separated Lists

Some common MATLAB operations and indexing techniques do not work directly on comma-separated lists. This section details several errors you can encounter when working with comma-separated lists and explains how to resolve the underlying issues.

Intermediate Indexing Produced a Comma-Separated List

Compound indexing expressions with braces or dots can produce comma-separated lists. You must index into the individual elements of the list to access them.

For example, create a 1-by-2 cell array that contains two 3-by-3 matrices of doubles.

A = {magic(3),rand(3)}
A =

  1×2 cell array

    {3×3 double}    {3×3 double}

Use brace indexing to display both elements.

A{1,:}
ans =

     8     1     6
     3     5     7
     4     9     2


ans =

    0.7922    0.0357    0.6787
    0.9595    0.8491    0.7577
    0.6557    0.9340    0.7431

Indexing into A this way produces a comma-separated list that includes both matrices contained by the cell array. You cannot use parentheses indexing to retrieve the entries at (1,2) in both matrices in the list.

A{1,:}(1,2)
Intermediate brace '{}' indexing produced a comma-separated list with 
2 values, but it must produce a single value when followed by 
subsequent indexing operations.

To retrieve the entries at (1,2) in both of the matrices in the cell array, index into the cells individually.

A{1,1}(1,2)
A{1,2}(1,2)
ans =

     1


ans =

    0.0357

Expression Produced a Comma-Separated List Instead of a Single Value

Arguments for conditional statements, logical operators, loops, and switch statements cannot be comma-separated lists. For example, you cannot directly loop through the contents of a comma-separated list using a for loop.

Create a cell array of the first three prime numbers.

A = cell(1,3);
A{1} = 2;
A{2} = 3;
A{3} = 5;

A{:} produces a comma-separated list of the three values.

A{:}
ans =

     2


ans =

     3


ans =

     5

Using for to loop through the comma-separated list generated by A{:} errors.

for c = A{:}
disp(c)
end
A brace '{}' indexing expression produced a comma-separated list with
3 values where only a single value is allowed.

To loop over the contents of A, enclose A{:} in square brackets to concatenate the values into a vector.

for c = [A{:}]
disp(c)
end
     2

     3

     5

Assigning Multiple Elements Using Simple Assignment

Unlike with arrays, using simple assignment to assign values to multiple elements of a comma-separated list errors. For example, define a 2-by-3 cell array.

B = cell(2,3);

Assigning a value of 5 to all cells of the array using : as an index for B errors.

B{:} = 5
Assigning to 6 elements using a simple assignment statement is not
supported. Consider using comma-separated list assignment.

One way to accomplish this assignment is to enclose B{:} in square brackets and use the deal function.

[B{:}] = deal(5)
B =

  2×3 cell array

    {[5]}    {[5]}    {[5]}
    {[5]}    {[5]}    {[5]}

Comma-Separated List Assignment to an Undefined Variable

You cannot assign a comma-separated list to an undefined variable using : as an index. In the example in Assigning to a Comma-Separated List, the variable x is defined as a comma-separated list with explicit indices before assigning new values to it using : as an index.

x{1} = []; 
x{2} = [];
[x{:}] = deal([10 20],[14 12]);
x{:}
ans =

    10    20


ans =

    14    12

Performing the same assignment with a variable that has not been initialized errors.

[y{:}] = deal([10 20],[14 12]);
Comma-separated list assignment to a nonexistent variable is not
supported when any index is a colon (:). Use explicit indices or
define the variable before performing the assignment.

To solve this problem, initialize y in the same way as x, or create y using enough explicit indices to accommodate the number of values produced by the deal function.

[y{1:2}] = deal([10 20],[14 12])
y =

  1×2 cell array

    {[10 20]}    {[14 12]}

See Also

| |