Preallocating a cell array of chars?

35 次查看(过去 30 天)
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
Stephen23 2020-10-27
编辑:Stephen23 2020-10-27
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 个评论
Monika Jaskolka
Monika Jaskolka 2020-10-27
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by