Haw to add new element of cell arrays?

138 views (last 30 days)
Mr M.
Mr M. on 26 May 2015
Edited: Stephen23 on 26 May 2015
I have a cell array of strings: {'abc','xyz','123'} and I would like to add a new element 'something' But I don't want to calculate the length of the array. Is it possible to join a new element to the end?

Accepted Answer

Stephen23
Stephen23 on 26 May 2015
Edited: Stephen23 on 26 May 2015
You can use the end operator:
A = {'abc','xyz','123'};
A{end+1} = 'something'
Note that while this is okay to do a few times within the code, do not do this inside a loop, as this continually expands the array and MATLAB must check the available memory and move the array as it enlarges. This is very inefficient and slow. Instead before a loop you should preallocate the cell array. This advice also applies to preallocating numeric arrays.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!