30

What is the difference between accessing elements in a cell array using parentheses () and curly braces {}?

For example, I tried to use cell{4} = [] and cell(4) = []. In the first case it sets the 4th element to [], but in the second case it wiped out the cell element, that is, reduced the cell element count by 1.

nbro
  • 15,395
  • 32
  • 113
  • 196
rajan sthapit
  • 4,194
  • 10
  • 42
  • 66
  • possible duplicate of [MATLAB and cell array handling in for loop](http://stackoverflow.com/questions/4635052/matlab-and-cell-array-handling-in-for-loop) – Jonas Jan 29 '12 at 17:45
  • The mathworks link [accessing cell array](http://www.mathworks.com/help/techdoc/matlab_prog/br04bw6-98.html) explains in a very lucid manner in order to get your concepts cleared and then you are ready to play with the arrays. – SKM Jan 29 '12 at 17:32

2 Answers2

69

Think of cell array as a regular homogenic array, whose elements are all cells. Parentheses (()) simply access the cell wrapper object, while accessing elements using curly bracers ({}) gives the actual object contained within the cell.

For example,

A={ [5,6], 0 , 0 ,0 };

Will look like this:

enter image description here

The syntax of making an element equal to [] with parentheses is actually a request to delete that element, so when you ask to do foo(i) = [] you remove the i-th cell. It is not an assignment operation, but rather a RemoveElement operation, which uses similar syntax to assignment.

However, when you do foo{i} = [] you are assigning to the i-th cell a new value (which is an empty array), thus clearing the contents of that cell.

Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
  • 3
    you can see cell as a list, which stores pointers to some thing else. With () you get the pointers, with {} you get things that the pointer point to. – gstar2002 Nov 04 '12 at 00:14
  • 1
    Another way of looking at it is that assigning to `[]` removes whatever you assign to. So `foo(i) = []` indeed removes the i-th cell, and `foo{i} = []` removes the content of the i-th cell. (Leaving nothing (`[]`) behind) – Dennis Jaheruddin Sep 30 '13 at 08:40
  • Take a look at this Octave documentation on cell arrays (MATLAB compatible ;)) https://www.gnu.org/software/octave/doc/v4.0.1/Indexing-Cell-Arrays.html#Indexing-Cell-Arrays] – loved.by.Jesus Jun 22 '16 at 13:40
3

See the help in this link. As you'll see, accessing with parentheses (), gives you a subset of a cell (i.e. a sub-cell), while curly braces {} gives you the content of the cell you are trying to access.

Jorge
  • 784
  • 5
  • 16
  • link is broken. Maybe it was pointing to https://www.mathworks.com/matlabcentral/answers/398071-difference-between-and#answer_317813 – wolf97084 May 31 '20 at 14:26