Preallocating a cell array of chars?

37 Ansichten (letzte 30 Tage)
Monika Jaskolka
Monika Jaskolka am 27 Okt. 2020
Kommentiert: Monika Jaskolka am 27 Okt. 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}

Akzeptierte Antwort

Stephen23
Stephen23 am 27 Okt. 2020
Bearbeitet: Stephen23 am 27 Okt. 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);
  1 Kommentar
Monika Jaskolka
Monika Jaskolka am 27 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by