Preallocating a cell array of chars?

37 ビュー (過去 30 日間)
Monika Jaskolka
Monika Jaskolka 2020 年 10 月 27 日
コメント済み: Monika Jaskolka 2020 年 10 月 27 日
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 Center および File ExchangeLogical についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by