Creating a cell array of size n

179 views (last 30 days)
I need a cell array of size n, like if n is 3, I need
C = {'red','red','red'}
If n is 100,
C = {'red','red',.......'red'}(100 cells)
I tried this,
C = cell(1,n);
for i = 1:n
C(i) = 'red';
This gives known error of conversion to cell from char is not possible.

Accepted Answer

James Tursa
James Tursa on 5 Jul 2012
Edited: James Tursa on 5 Jul 2012
The most memory efficient way is the following without a loop:
C(1:n) = {'red'}; % Assuming C doesn't exist yet (EDITED)
That is because in the above line, all n copies of the 'red' string are reference copies of each other (like a shared data copy), so the memory footprint is smaller than filling each cell individually with a brand new allocated string in a loop.
Having said that, I strongly suspect that what you are attempting to do is futile. If you change any of the individual 'red' strings downstream in your code you will probably need to allocate brand new cell element variables anyway, so this pre-allocation of 'red' would be useless (actually wastes time) regardless of the methoud you use to create C in the first place (my method or with a loop). The only exceptions would be if you don't plan on altering C at all downstream, or if you plan to operate on each string "in-place" ... i.e., changing the contents of the string directly without changing its length, etc. Can you elaborate on what you intend to do with C downstream in your code?
James Tursa
James Tursa on 5 Jul 2012
P.S. My comments also apply to Jan's answer, since it essentially does the same thing.

Sign in to comment.

More Answers (3)

Jan on 5 Jul 2012
C = cell(1, n);
C(:) = {'red'};

F. on 5 Jul 2012
Your error :
C(i) = 'red';
C is a cell array, with C(i) you reach the place in the cell array and not the element which is in this place. So try :
C{i} = 'red';
Giuseppe Degan Di Dieco
Giuseppe Degan Di Dieco on 19 May 2021
Dear F,
thanks for your explanation of the cell array object.
Actually, it was quite tricky to understand.

Sign in to comment.

grapevine on 5 Jul 2012
You have to modify your code in this way :
C = cell(1,n);
for i = 1:n
C(i) = java.lang.String('red');
Another solution could pass by using the function: char2cell, which is available on Matlab Central Exchange
good luck
grapevine on 9 Jul 2012
Edited: grapevine on 9 Jul 2012
Weird! it works for me. read the doc :)

Sign in to comment.


Find more on Data Type Conversion in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!