shashashamti2008
shashashamti2008

Reputation: 2327

MATLAB: A{:} vs A(:) when A is a cell array

If A is a cell array in MATLAB, I wanted to learn the difference between A{:} and A(:) and where I should them.

Upvotes: 0

Views: 1534

Answers (1)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23685

As you can read in official documentation, the former refers to indexing a set of cells in the array (actually, all of them) and the latter refers to indexing a set of underlying values in the array (again, all of them).

Cell arrays are nothing but homogenic arrays whose elements are all cells, and cells have an underlying value that can be of any type. Round parentheses simply access the cells (the wrapping objects of the underlying values), while curly braces access the elements wrapped by the cells themselves (the underlying values).

Let's make a quick example. Round parentheses will return a cell array, since a single colon operator (:) is used and the matrix is flattened:

A = {1 2; 3 4};
A(:)

ans =

  4×1 cell array

    [1]
    [3]
    [2]
    [4]

Curly braces, on the opposite, will return the underlying value of each cell (doubles):

A = {1 2; 3 4};
A{:}

ans =

     1

ans =

     3

ans =

     2

ans =

     4

In this second case, if you want an array to be returned, you have to write the selector as follows:

[A{:}]

ans =

     1     3     2     4

Upvotes: 5

Related Questions