Preallocating cell array concent

조회 수: 62 (최근 30일)
Steeven
Steeven 2018년 4월 13일
편집: Stephen23 2018년 4월 13일
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?

답변 (2개)

Stephen23
Stephen23 2018년 4월 13일
편집: Stephen23 2018년 4월 13일
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 2018년 4월 13일
data = cell(1,8) ;
data(:) = {NaN(3,5)} ;

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by