0

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.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Argyll
  • 8,591
  • 4
  • 25
  • 46

2 Answers2

3

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).

Edric
  • 23,676
  • 2
  • 38
  • 40
  • 2
    "The penalty for growing arrays dynamically is much less severe than it used to be" -- But this is when you grow like Adriaan does in the other answer, not when growing by concatenation. See here for an experiment, which is still valid in R2021b (I just verified this): https://stackoverflow.com/q/48351041/7328782 – Cris Luengo Mar 29 '22 at 15:11
  • 1
    @CrisLuengo: That's very interesting. I am a bit surprised that the concatenation syntax likely induced copying or preparation for a deep copy. That is good to keep in mind. – Argyll Mar 30 '22 at 01:23
  • 2
    Good point @CrisLuengo, I was indeed thinking of indexing-growing rather than repeated concatenation. I don't know, but I suspect the repeated concatenation case is somewhat harder to optimise - but there's definitely _something_ going on because repeated concatenation is _much_ faster inside a function than at the command-line, which is usually an indication that an optimisation has been applied. – Edric Mar 30 '22 at 07:46
2

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.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • purely FYI, you might be interested in [empty](https://www.mathworks.com/help/matlab/ref/empty.html) – Argyll Mar 29 '22 at 07:15