Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Preallocate char array - better way than char(zeros(10,4))?

450 views
Skip to first unread message

spasmous

unread,
Feb 12, 2009, 8:51:24 PM2/12/09
to
I need an empty array of chars. With numeric types you can specify
zeros(10,4,'uint8') or whatever however I would like chars. Typing
zeros(10,4,'char') doesn't work so I'm using char(zeros
(10,4,'uint8')). This is a bit ugly - anyone got another suggestion?
Thanks.

Doug Schwarz

unread,
Feb 12, 2009, 9:03:34 PM2/12/09
to
In article
<a34f67e2-4f57-4804...@t3g2000yqa.googlegroups.com>,
spasmous <spas...@gmail.com> wrote:

A couple of possibilities:

1. x = repmat(char(0),10,4);

2. x(10,4) = char(0);


I prefer #1 because it will always work whereas #2 requires that there
is no x variable already in existence. You can precede it with clear x,
but then it's even messier.

--
Doug Schwarz
dmschwarz&ieee,org
Make obvious changes to get real email address.

Christoph Budziszewski

unread,
Aug 2, 2011, 3:48:09 PM8/2/11
to

I tested with tic-toc:
x = char(zeros(1,100));
Elapsed time is 0.000033 seconds.
is faster than
y = repmat(char(0),1,100);
Elapsed time is 0.000263 seconds.
is faster than
z = char(zeros(1,100,'uint8'));
Elapsed time is 0.001665 seconds.

Doug Schwarz <s...@sig.for.address.edu> wrote in message <see-0D97FE.2...@news.frontiernet.net>...

Jan Simon

unread,
Aug 2, 2011, 6:35:09 PM8/2/11
to
Dear Christoph,

> x = char(zeros(1,100));
> Elapsed time is 0.000033 seconds.

> y = repmat(char(0),1,100);


> Elapsed time is 0.000263 seconds.

> z = char(zeros(1,100,'uint8'));


> Elapsed time is 0.001665 seconds.

Other timings (Matlab 2009a):
tic; for i=1:1000,
x = repmat(char(0), 1, 100);
clear('x'); end; toc;
>> 0.051 sec

tic; for i=1:1000,
x = char(zeros(1, 100));
clear('x'); end; toc;
>> 0.021 sec

tic; for i=1:1000,
x = char(zeros(1, 100, 'uint8'));
clear('x'); end; toc;
>> 0.017 sec

tic; for i=1:1000,
b = char(0);
x = b(ones(1, 100));
clear('x'); end; toc;
>> 0.025 sec

Clearing the created variable in the loop makes the problem more realistic. Otherwise Matlab's smart JIT seems to understand more or less, that the repeated work is not necessary.

My conclusion: For real world problems, all methods will be sufficiently fast.

Kind regards, Jan

James Tursa

unread,
Aug 3, 2011, 1:04:13 PM8/3/11
to

Bruno Luong

unread,
Aug 3, 2011, 6:29:13 PM8/3/11
to
"James Tursa" wrote in message <j1bv2d$4gi$1...@newscl01ah.mathworks.com>...

> You can find the UNINIT utility here:
>
> http://www.mathworks.com/matlabcentral/fileexchange/31362-uninit-create-an-uninitialized-variable-like-zeros-but-faster
>

I never feel a need of optimizing my codes at such level of detail, but surely such function should be part of Matlab.

Bruno

0 new messages