How to append an empty array to a cell array

1k Views Asked by At

How do you append an empty array to a (non-empty) cell array?

For example, starting with

c={[1],[2]}

desire

c={[1],[2],[]}

Concatenation would remove the empty array whether it is double, char or cell.

2

There are 2 best solutions below

1
Adriaan On BEST ANSWER

You can just append it by using end+1:

c={[1],[2]}
c = 
    [1]    [2]
c{end+1} = []  % end+1 "appends"
c = 
    [1]    [2]    []

MATLAB note: appending is usually used as a way to grow an array in size within a loop, which is not recommended in MATLAB. Instead, use pre-allocation to initially apply the final size whenever possible.

3
Edric On

In addition to @Adriaan's answer, note that you can also do this with concatenation, if you are careful.

>> c = {1, 2}
c =
  1x2 cell array
    {[1]}    {[2]}
>> [c, {[]}]
ans =
  1x3 cell array
    {[1]}    {[2]}    {0x0 double}

The trick here is to concatenate explicitly with another cell (your question suggests you tried [c, []] which does indeed do nothing at all, whereas [c, 1] automatically converts the raw 1 into {1} before operating).

(Also, while pre-allocation is definitely preferred where possible, in recent versions of MATLAB, the penalty for growing arrays dynamically is much less severe than it used to be).