How to use cell arrays in Matlab?

With cell arrays you have two methods of indexing namely parenthesis (i.e. (...)) and braces (i.e. {...}).

Lets create a cell array to use for examples:

A = {3,   9,     'a'; 
     'B', [2,4], 0};

Indexing using paranthesis returns a portion of the cell array AS A CELL ARRAY. For example

A(:,3)

returns a 2-by-1 cell array

ans="a"
     0

Indexing using braces return the CONTENTS of that cell, for example

A{1,3}

returns a single character

ans =

a

You can use parenthesis to return a single cell as well but it will still be a cell. You can also use braces to return multiple cells but these return as comma separated lists, which is a bit more advanced.

When assigning to a cell, very similar concepts apply. If you’re assigning using parenthesis, then you must assign a cell matrix of the appropriate size:

A(:,1) = {1,1}

if you assign a single value using parenthesis, then you must put it in a cell (i.e. A(1) = 2 will give you an error, so you must do A(1) = {2}). So it’s better to use braces as then you are directly affecting the contents of the cell. So it is correct to go

A{1} = 2

this is equivalent to A(1) = {2}. Note that A{1} = {2}, which is what you’ve done, will not give a error but what is does is nests a cell within your cell which is unlikely what you were after.

Lastly, if you have an matrix inside one of your cells, then Matlab allows you to index directly into that matrix like so:

A{2,2}(1)

ans = 

     3

Leave a Comment