preallocating a cell array of strings

  • Follow


I am trying to pre-allocate a cell array of strings. I can do the following:

test = cell(m,1);
for i = 1:m
test{i} = 'test';
end;
unique(test);

But I thought there may be a better solution somewhere. The main thing is being able to do unique(test);

TIA
ct
0
Reply C 4/9/2010 4:17:26 PM

"C T" <usro@doramail.com> wrote in message <hpnjul$3vs$1@fred.mathworks.com>...
> I am trying to pre-allocate a cell array of strings. I can do the following:
> 
> test = cell(m,1);
> for i = 1:m
> test{i} = 'test';
> end;
> unique(test);

Generally there is no gain to preallocate elements of cell if you intend to replace them later (this situation likely happens when using cell). See this thread for more detailed discussion:

http://www.mathworks.com/matlabcentral/newsreader/view_thread/258931

Bruno
0
Reply Bruno 4/9/2010 4:33:24 PM


"C T" <usro@doramail.com> wrote in message <hpnjul$3vs$1@fred.mathworks.com>...
> I am trying to pre-allocate a cell array of strings. I can do the following:
> 
> test = cell(m,1);
> for i = 1:m
> test{i} = 'test';
> end;
> unique(test);
> 
> But I thought there may be a better solution somewhere. The main thing is being able to do unique(test);
> 
> TIA
> ct

test = cell(m,1);
test(:) = {'test'};

This will cause each cell to share the same physical variable 'test', so not much wasted space even if m is very large. Also gets rid of the [] cells so you can use unique.

James Tursa
0
Reply James 4/9/2010 4:44:22 PM

2 Replies
236 Views

(page loaded in 0.148 seconds)

Similiar Articles:













7/26/2012 3:40:34 PM


Reply: