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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

"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): stackoverflow.com/q/48351041/7328782
@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.
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.
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.

1 Comment

purely FYI, you might be interested in empty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.