Preallocating a cell array of chars?

34 visualizaciones (últimos 30 días)
Monika Jaskolka
Monika Jaskolka el 27 de Oct. de 2020
Comentada: Monika Jaskolka el 27 de Oct. de 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}

Respuesta aceptada

Stephen23
Stephen23 el 27 de Oct. de 2020
Editada: Stephen23 el 27 de Oct. de 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 comentario
Monika Jaskolka
Monika Jaskolka el 27 de Oct. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by