Preallocating cell array concent

59 views (last 30 days)
Steeven
Steeven on 13 Apr 2018
Edited: Stephen23 on 13 Apr 2018
I can preallocate the contents of a usual matrix/vector/array with
test(1:8)=nan
giving the result:
This way of reaching each element in an array by typing 1:8 is one of the very useful features of MatLab.
But can I do the same to a cell array? For example:
data = cell(1,8)
data{1:8} = NaN(3,5)
The NaN(3,5) creates a matrix full of NaN values. So, here I first allocate memory for 8 cells in the cell array and then I wish to reach each of these 8 cells by writing data{1:8} and add a NaN-matrix in each of them.
This does not work but gives me:
Apparently the 1:8 syntax does not work inside curly brackets.
So, what is the method for preallocating the content of each cell in a cell array, when they are must simply get the same size and content? Can I not avoid a for loop?

Answers (2)

Stephen23
Stephen23 on 13 Apr 2018
Edited: Stephen23 on 13 Apr 2018
Simple:
data = cell(1,8)
data(1:8) = {NaN(3,5)}
How does this work? Compare to your numeric example:
test(1:8) = nan
Where
  • We want to allocate the RHS (a scalar numeric) to multiple numeric elements on the LHS.
  • MATLAB uses scalar expansion to put that scalar element (numeric) into all elements (numeric) of the LHS variable.
Exactly the same applies to a cell array:
  • We want to allocate the RHS (a scalar cell array) to multiple cells on the LHS.
  • MATLAB uses scalar expansion to put that scalar element (cell) into all elements (cell) of the LHS variable.
This scalar expansion does not apply to the contents of the cell array (like you were attempting with curly braces {}) but to the cell arrays themselves (which can be accessed using parentheses ()). See also:
Another option would be to use a comma-separated list and deal, but I would not recommend doing this because the first solution is much simpler:
[data{1:8}] = deal(NaN(3,5))

KSSV
KSSV on 13 Apr 2018
data = cell(1,8) ;
data(:) = {NaN(3,5)} ;

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!