# Preallocating a cell array of chars?

56 views (last 30 days)
Monika Jaskolka on 27 Oct 2020
Commented: Monika Jaskolka on 27 Oct 2020
Is there a better way of preallocating a cell array of empty chars than using a for loop or deal? Cells can contain any data type, yet if I create a empty cell array, it is always type double.
>> A = cell([3,1])
A =
3×1 cell array
{0×0 double}
{0×0 double}
{0×0 double}
>> for i = 1:length(A), A{i} = ''; end
>> A
A =
3×1 cell array
{0×0 char}
{0×0 char}
{0×0 char}

Stephen23 on 27 Oct 2020
Edited: Stephen23 on 27 Oct 2020
A = cell(3,1);
A(:) = {''}
This assigns one scalar cell (on the RHS) to all of the cells in the array A:
Or simply use
A = repmat({''},3,1);
Monika Jaskolka on 27 Oct 2020
Thanks. Looks like the your first approach is fastest for my case.
>> len = 1000000;
>> A = cell([len, 1]); tic; A(:) = {''}; toc % assignment
Elapsed time is 0.013068 seconds.
>> A = cell([len, 1]); tic; A = repmat({''},len,1); toc % repmat
Elapsed time is 0.024813 seconds.
>> A = cell([len, 1]); tic; for i = 1:length(A), A{i} = ''; end, toc % for loop
Elapsed time is 0.183295 seconds.
>> A = cell([len, 1]); tic; [A{:}] = deal(''); toc % deal
Elapsed time is 0.293894 seconds.

### Categories

Find more on Matrices and Arrays in Help Center and File Exchange

R2020a

### Community Treasure Hunt

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

Start Hunting!