I want to initialize a very large character array with the same character string

109 ビュー (過去 30 日間)
David
David 2013 年 6 月 4 日
The array is so large it takes forever for MATLAB to do it with a simple loop, e.g.;
for i = 1:N A(i) = 'String' end
I know this can be done numerically using ones (* the desired value) in a single line of code. Can it be done with a character string in a way that speeds up the process?
Thanks, David
  1 件のコメント
Jan
Jan 2013 年 6 月 4 日
編集済み: Jan 2013 年 6 月 4 日
The shown loop cannot work, because you try to assign a CHAR vector to a scalar element. What is the wanted result? Do you want a cell string {'String', 'String', ...} or a CHAR vetor 'StringString...'?

サインインしてコメントする。

回答 (2 件)

Iain
Iain 2013 年 6 月 4 日
char_array = char(ones(N,1) * 'String');
cell_version = repmat({'String'},N,1);

Ahmed
Ahmed 2013 年 6 月 4 日
Have you tried 'repmat'?
N = 100000;
A = repmat('String',N,1);
If you must use a for-loop, you should pre-allocate the array. If uninitialized, the growing of the array will consume a lot of time. Here, an example of preallocation and filling with loop.
N = 100000;
A = repmat(char(0),N,6);
for i = 1:N, A(i,:) = 'String'; end
  1 件のコメント
Jan
Jan 2013 年 6 月 4 日
It is much faster to operate on the columns and assign scalars:
N = 100000;
A = repmat(char(0),N,6);
S = 'String';
for k = 1:6
A(:, k) = S(k);
end

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by