Cell Arrays and Their Contents 117
Posted by Loren Shure,
I've written several blog articles so far on structures, and not quite so much on their soulmates, cell arrays. Just last week, at the annual MathWorks Aerospace Defense Conference (MADC), I had several people ask for help on cell arrays and indexing. Couple that with the weekly questions on the MATLAB newsgroup, and it's time.
Here's my mnemonic for remembering when to use the curly braces: curly for contents Does anyone have any mnemonics or
other special ways to help remember when to use the different kinds of indexing? If so, please post here.
Contents
Arrays
As you probably already know, arrays in MATLAB are rectangular looking in any two dimensions. For example, for each row in a matrix (2dimensional), there is the same number of elements  all rows have the same number of columns. To denote missing values in floating point arrays, we often use NaN. And each MATLAB array is homogeneous; that is, each array element is the same kind of entity, for example, double precision values.Cell Arrays
Cell arrays were introduced in MATLAB 5.0 to allow us to collect arrays of different sizes and types. Cell arrays themselves must still be rectangular in any given two dimensions, and since each element is a cell, the array is filled with items that are all the same type. However, the contents of each cell can be any MATLAB array, including numeric arrays, the ones that people typically first learn
 strings
 structures
 cell arrays
clear
Indexing Using Parentheses
Indexing using parentheses means the same thing for all MATLAB arrays. Let's take a look at a numeric array first and then a cell array.M = magic(3)
M = 8 1 6 3 5 7 4 9 2Let's place a single element into another array.
s = M(1,2)
s = 1Next let's get a row of elements.
row3 = M(3,:)
row3 = 4 9 2And now grab the corner elements.
corners = M([1 end],[1 end])
corners = 8 6 4 2What's in the MATLAB workspace?
whos
clear % clean up before we move forward
Name Size Bytes Class M 3x3 72 double array corners 2x2 32 double array row3 1x3 24 double array s 1x1 8 double array Grand total is 17 elements using 136 bytesNext, let's do similar experiments with a cell array.
C = {magic(3) 17 'fred'; ... 'AliceBettyCarolDianeEllen' 'yp' 42; ... {1} 2 3}
C = [3x3 double] [17] 'fred' [1x25 char ] 'yp' [ 42] {1x1 cell } [ 2] [ 3]Notice the information we get from printing C. We can see it is 3x3, and we can see information, but not necessary full content, about the values in each cell. The very first cell contains a 3x3 array of doubles, the second element in the first row contains the scalar value 17, and the third cell in the first row contains a string, one that is short enough to print out. Let's place a single element into another array.
sCell = C(1,2)
sCell = [17]Next let's get a row of elements.
row3Cell = C(3,:)
row3Cell = {1x1 cell} [2] [3]And now grab the corner elements.
cornersCell = C([1 end],[1 end])
cornersCell = [3x3 double] 'fred' {1x1 cell } [ 3]What's in our workspace now?
whos clear sCell row3Cell cornersCell
Name Size Bytes Class C 3x3 774 cell array cornersCell 2x2 396 cell array row3Cell 1x3 264 cell array sCell 1x1 68 cell array Grand total is 84 elements using 1502 bytes
An Observation about Indexing with Parentheses
When we index into an array using parentheses, (), to extract a portion of an array, we get an array of the same type. With the double precision array M, we got double precision arrays of different sizes and shapes as our output. When we do the same thing with our cell array C, we get cell arrays of various shapes and sizes for the output.Contents of Cell Arrays
Cell arrays are quite useful in a variety of applications. We use them in MATLAB for collecting strings of different lengths. They are good for collecting even numeric arrays of different sizes, e.g., the magic squares from order 3 to 10. But we still need to get information from within given cells, not just create more cell arrays using (). To do so, we use curly braces {}. I used one set of them to create C initially. Now let's extract the contents from some cells and assign the output to an array. Let's place a single element into another array.m = C{1}
m = 8 1 6 3 5 7 4 9 2Next let's try to get a row of elements.
try row3 = C{3,:} catch lerr = lasterror; disp(lerr.message(24:end)) end
Illegal right hand side in assignment. Too many elements.Why couldn't I do that? Let's look at what's in row 1.
C(1,:)
ans = [3x3 double] [17] 'fred'Now let's see what we get if we look at the contents without assigned the output to a variable.
C{1,:}
ans = 8 1 6 3 5 7 4 9 2 ans = 17 ans = fredYou can see that we assign to ans three times, one for each element in the row of the cell array. It's as if we wrote this expression: C{1,1},C{1,2},C{1,3} with the output from these arrays being successively assigned to ans. MATLAB can't typically take the content from these cells and place them into a single array. We could extract the contents of row 1, one cell at a time as we did to create m. If we want to extract more cells at once, we have to place the contents of each cell into its own separate array, like this,
[c11 c12 c13] = C{1,:}
c11 = 8 1 6 3 5 7 4 9 2 c12 = 17 c13 = fredtaking advantage of syntax new in MATLAB Release 14 for assignment when using commaseparated lists.
Cell Array Indexing Summary
 Use curly braces {} for setting or getting the contents of cell arrays.
 Use parentheses () for indexing into a cell array to collect a subset of cells together in another cell array.
117 CommentsOldest to Newest
*note: random comment not necessarily related to your recent post*
Loren:
I’m a fairly new Matlab user, but I still enjoy reading your postings. Just out of curiousity:
Is this you? why(61)?
Engineering freshmen never get tired of this command.
Joey
Joey
I guess so, but I didn’t program that myself!
–loren
I don’t have another mnemonic for the braces problem, but it helps me when i think about it this way:
– cells are like wrappers around some content.
– as Loren said, normal subscripting/indexing using () results in the same data type, which is cell. think of it as of splitting the cell.
– the curly braces dereference (or extract) the wrapped content. For people familiar with e.g. C++ this might help, as it resembles in some ways dereferencing pointers.
Just as an aside: sometimes i think notation in matlab is a bit cumbersome. Take e.g. an array of structs. Now you want to assign to a number of these structs the same value to a certain field. currently this can be achieved by:
[s(1:3).val] = deal(5)
if i wanted to assign 5 to all fields named ‘val’ in the structs s(1:3). This notation is a bit lengthy and complicated, why not just:
s(1:3).val = 5
This would be consistent with the syntax used for numeric arrays and is afaik unambigous.
Michael
Michael
I have entered your suggestion into our enhancement database. I think scalar expansion is generally very useful.
–Loren
hi,
your blogs are very nice
Thanks for the great demystification of “cell” and “content” indexing of cell arrays. Your article should become part of the handbook!
hey loren
i’m wondering why the following syntax does not work:
x=dir
a{2:4}={x(3:5).name}
erik
Erik
Because
1) MATLAB requires you to use [] for multiple lefthand sides.
2) You only have a single righthand side.
Try this instead:
–Loren
ah great. thanks. i understand why my curly’s on the right side were a bad idea. but i don’t understand why the squares are necessary on the left. isn’t the intent unambiguous without them?
erik
Perhaps the intent is, but that’s not MATLAB. We could extend it that way, but that might end up being more confusing rather than less. The lefthand side I wrote is actually 3 distinct outputs. MATLAB currently requires multiple outputs to be enclosed between [].
–l
This is a wonderful insight! Is there more discussion of this in the documentation? The only thing I could find was this brief line under the brief discussion of square brackets under Special Characters
“For the use of [ and ] on the left of an “=” in multiple assignment statements, see lu, eig, svd, and so on.”
ah ha — i am remembering now why i feel like my original approach should work. why isn’t the following analogy appropriate? single lhs, single rhs.
b(3:5) = [1 2 3]
there shouldn’t be any need to invoke the “multiple outputs/commaseparated lists” stuff, should there?
erik
As with many things in MATLAB, singletons are treated differently. With one output, you can, but do not need to use, the square brackets.
See this part of the documentation,
particularly the section on “MATLAB Function Syntax.” I looked under MATLAB Programming, found a section called “Calling Functions”, went to the section on “MATLAB Calling Syntax” and found it in a subheading in that section.
–loren
right, but i’m trying to say that in:
(1) a{2:4}={x(3:5).name}
both sides are singletons, just as in:
(2) b(3:5) = [1 2 3]
i don’t get why (1) is unacceptable, since (2) is so standard.
erik
Erik
Your lefthand side in the first equation is NOT a singleton. It has 3 elements. It’s the same as this commaseparated list:
3 arrays with potentially different sizes/types.
The second case IS a singleton. It’s a 1×3 array. That’s different than 3 arrays as in the first case.
The cases you state are quite different from one another. It is possible for MathWorks to consider adding the syntax you would like to MATLAB. I don’t yet find it compelling myself.
–Loren
ah, i see, yes my lhs is not singleton. but a(2:4) is. so the following works!
a(2:4)={x(3:5).name}
this approach also works preR14, unlike the multiple LHS square bracket approach. does this contradict the guideline: “use curlys for setting/getting,” or am i misunderstanding the guideline?
this is why i have such a hard time using cell arrays — i think “i have a cell array, i have to use curlys.” but then there are these situations where it is much more natural (and legal) to use parens. so the whole cell array distinction breaks down for me. looking at the cell array chapter of the help, i see that this is the “content vs. cell indexing” issue, which i must admit baffles me. as an experienced programmer in many other languages, this whole cell thing is the most irksome part of matlab — other languages do not need a separate syntax/object model for hierarchically nested dynamically/heterogeneously sized compound types. so this complexity in matlab’s design always feels unnatural to me.
erik
Erik
Look carefully at what you get here. You get the one cell array {x(3:5).name} of size 1×3 scalar expanded so that a(2) equals a(3) and a(4). The contents are duplicated, not distributed among the output vector.
–Loren
unless i’m misunderstanding you, that’s not what i think i’m getting:
>> x=dir
x =
30×1 struct array with fields:
name
date
bytes
isdir
>> a(3:5)={x(2:4).name}
a =
[] [] ‘AUTOEXEC.BAT’ ‘CONFIG.SYS’ ‘Config.Msi’
>> a(2)
ans =
{[]}
>> a(3)
ans =
‘AUTOEXEC.BAT’
>> a(4)
ans =
‘CONFIG.SYS’
>> a{2}
ans =
[]
>> a{3}
ans =
AUTOEXEC.BAT
>> a{4}
ans =
CONFIG.SYS
erik
Erik
Of course, you are right. When I replied I was not thinking clearly at all and thought you had 3 outputs on the left and one righthand side. You are actually copying part of a cell array to another cell array of the same size – one righthand side, one lefthand side.
–Loren
hey loren –
no problem! what you just wrote is a perfect explanation for why a{2:4}=x(3:5).name should work. rather than returning “multiple right hand sides,” i think it would be much clearer if expressions like this always implicitly returned a singleton cell array of results. the whole “multiple this’s and that’s” thing is pretty strange, and i think you’d agree it causes much confusion. are there examples of ambiguous cases where just packaging things up into cell array singletons would not be appropriately expressive?
i think the confusion is just evidence that the cell array design is not so userfriendly. i know matlab is locked into cell arrays at this point, but hypothetically, would a native string type solve all the issues that cell arrays were designed to solve? just like i can have a multidimensional array of int8’s or structs, i could have a multidimensional array of strings?
come to think of it, i am attracted to the simplicity of syntax in languages that stick to purity — in lisp, everything is a list. in java/python/smalltalk, everything is an object (well… mostly). in c, everything is a void * (even functions). that seems to me to avoid the difficulties of having stuff jammed into a datatype and you are left unable to figure out how to get it back out or assign it. in matlab, everything could be a multidimensional array that is agnostic as to the types/sizes of its entries — which would themselves be multidimensional arrays. at the bottom would be singleton atomic types — strings, int8’s, structs, doubles, etc. actually, i guess this is what a cell array is — so rather than arguing for getting rid of cell arrays, i’m arguing for getting rid of regular arrays, changing all the builtins to expect cell array arguments instead of numeric matrices, etc. in case i send a multidimensional array that is half strings and half structs to svd(), it could just tell me i’m being silly.
anyway, since i don’t seriously expect matlab to make such a drastic change, could you summarize how and when to chose parens vs. curlies? the “get and set with curlies” doesn’t seem to be quite right, as per the above example. is there a performance difference or other consideration that gives a preference between
[a{2:4}]=x(3:5).name
and
a(2:4)={x(3:5).name}
?
i am not so fond of the perl philosophy “provide 18 ways to do the same thing.” because when you are trying to understand how to use something and remember it 3 weeks from now, it is just confusing if there are lots of options with very subtle differences (parens vs. curlies, for example) that have no semantic impact — not to mention lots of similar variations that have unambiguous semantic intent, but are syntactically disallowed. this is what makes it hard to “think in matlab,” in my opinion — i can’t just express my natural intent of “stick these three strings in these positions of that array” — i have to worry about curlies and squares and parens and multiple left hand sides, etc. i like freedom and options, but only when they are meaningful and actually let me do new things. for instance, i wouldn’t like it if matlab let me use pound signs and backquotes to stand for equals signs (but only on thursdays), just so i had more “options.” that’s a bit what the paren vs. curly distinction feels like to me right now. two semiincompatible ways to do indexing feels like one too many. my (very intelligent and skilled programmer) boss refuses to use cell arrays in matlab and will not read or work with my code because i do use them! :)
that reminds me of one last language design question i have. in the above discussion, rather than having to store x=dir, wouldn’t it be nice to be able to index the result of dir directly? it is a longstanding standard in programming languages that parens are for function args and squares are for indexing. so it would be natural for dir[5].name to mean “the name of the fifth result of dir.” but since matlab uses parens for both function calls and indexing, i will never be able to write dir(5) for these semantics, because that looks like a call to the dir function with an argument of 5. the best i could do is the very ugly dir()(5). and if dir() returns a *function*, i am again stuck. why did matlab choose to overlap the syntax for function args and indexing?
sorry for the overly philosophical and selfimportant post. these are just things that have been brewing in the mind of a relatively experienced programmer who has been trying to become proficient at matlab over the past 2 years and sometimes is frustrated by the design decisions — if i understood their rationale then my frustration would go away.
erik
sorry to be annoying, just thought the following was amusing/illustrative. i remember about a year ago it being late at night and i was under a deadline, and trying to figure out how to use a cell array (for like the third time — it just never sticks). after each line i remember wanting to throw my computer out of the window and thinking “it is so fricking obvious what i want, you obstinate junkpile…”
the transcript was something like:
>> a{2:4}=x(3:5).name
??? Illegal right hand side in assignment. Too many elements.
>> a{2:4}={x(3:5).name}
??? Insufficient outputs from right hand side to satisfy comma separated
list expansion on left hand side. Missing [] are the most likely cause.
>> [a{2:4}]={x(3:5).name}
??? Insufficient outputs from right hand side to satisfy comma separated
list expansion on left hand side. Missing [] are the most likely cause.
>> a{2:4}=[{x(3:5).name}]
??? Insufficient outputs from right hand side to satisfy comma separated
list expansion on left hand side. Missing [] are the most likely cause.
>> a{2:4}=deal({x(3:5).name})
??? Insufficient outputs from right hand side to satisfy comma separated
list expansion on left hand side. Missing [] are the most likely cause.
>> a{2:4}=deal(x(3:5).name)
??? Error using ==> deal
The number of outputs should match the number of inputs.
>> a{2:4}=[x(3:5).name]
??? Insufficient outputs from right hand side to satisfy comma separated
list expansion on left hand side. Missing [] are the most likely cause.
>> {a{2:4}}=x(3:5).name
??? {a{2:4}}=x(3:5).name

Error: Missing operator, comma, or semicolon.
>> {a{2:4}}={x(3:5).name}
??? {a{2:4}}={x(3:5).name}

Error: Missing operator, comma, or semicolon.
… and so on for many lines…
all of the above still seem totally reasonable to me. by the end i was reduced to a shaking red eyed ogre and wanted to peel my fingernails off. i just do not have these kinds of problems in c, lisp, java, or even perl. ok maybe a little bit in lisp. the backquote is still hard on me. prolog’s negation and > semantics are the only fundamental language constructs i can think of right now that torment me like cell arrays.
incidentally, here is correct way #3:
[a{2:4}]=deal(x(3:5).name)
Erik
The reason for the multiple lefthand sides has to do with keeping consistency across all of MATLAB for the commaseparated list. If you keep that in mind (and don’t answer posts while distracted!), you should find it fairly easy to keep track of.
The indexing into an expression is something that we have heard before. It is on the enhancement list – no date promised.
–Loren
Erik
Correction for you. An even better way for you to do the data distribution is:
Multiple rhs, multiple lhs.
–Loren
Given I have a cell array “d” which contains a series of column vectors (different lengths) containing dates; I would like to take the union of all these dates.
If union() took muliple arguments like isequal() then I could write union(d{:}). But since union() only unions two arguments, I’ll have to write somethign like this:
union(union(union(union(d{1}, d{2}), d{3}), d{4}), …
Is there a shorthand way to write the above?
thanks.
/m
Mohammed
I think you could do this instead:
Thats a good way, but there are two issues with that. First unique() tends to do an unwanted sort, and second its not generic enough to directly apply to some other set operation such as intersect() or setdiff().
I am using the following to do the job:
s = d{1}; for i = 2:length(d) s = union(s,d{i}); end
it works, but its not neat!
/m
ps. I find your blog inspiring. Thanks.
wow this is interesting ..
but i had doubt that how to get tha output in the array format.??
Hello!
I faced a big problem while I worked on a project!
I have a Cell array in MATLAB which contains Symbolic objects. I wanna print it, and wanna see content of cells! but when I use “celldisp” or when I type the name of cell array, it just show me that it`s components are “sym 1*1”, Or show the contents in different lines ( I mean it doesnt show cell contents in an organized format), How can I see or print this cell array?!
Tanx!
Sina
You currently would need to create your own print routine.
–Loren
Hi,
I am a novice MATLAB user, currently using it for an oceanographic project. I have ASCII data from 30 stations, essentially ‘mx7’ matrices, where 98
*attempt to resend; don’t know if initially received*
Hi,
I am a novice MATLAB user, currently using it for an oceanographic project. I have ASCII data from 30 stations, essentially ‘mx7’ matrices, where 98
Sina
my little script below may help to print your objects.
%% read fieldnames in cell
s_fieldnames=fieldnames(S); % S is your Cell array
s1_fieldnames=char(s_fieldnames);
%% convert field names in cell array into corresponding variable name
for m=1:length(s_fieldnames),
s2_fieldnames=textscan(horzcat(s1_fieldnames(m,:)),’%s’);
s2_fieldnames=char(s2_fieldnames{1,1});
%% store original value in variable
eval([s2_fieldnames,’=getfield(S,”’,char(s_fieldnames(m)),”’);’]);
end;
clear S s_fieldnames s1_fieldnames s2_fieldnames m
% then print the variables from the Matlab workspace
Dear Loren,
I’m writing a Matlab code which reads an Excel file and stores data in two matrices: ‘a’ and ‘b’, the latter being a cell matrix.
In the first column of ‘b’ matrix, the user is mandatory to type a 3character word. In the second column, it is optional to type anything.
If the user fills the second column of ‘b’, this word must be printed. On the other hand, if one does not fill this second column, the content of the first column must be printed. This is accomplished by using an ‘if’ statement and this is my problem when trying to do so.
My question is: if the content of a ‘b’ element is empty (the user did not type anything) how can I make an ‘if’ test in order to identify this empty content?
I tried if b{2,2} = [] but Matlab returned an error message.
Thank you for your attention.
Andre
Andre
Have you tried if isempty(b{2,2})? If it’s not empty, what’s in there – blanks?
–Loren
Dear Loren,
Actually, I didn’t try ‘isempty’.
I’m going to do this.
Thank you very much!
Andre
I have a problem with cell array.
With array, it’s quite easy to reorder.
For example if I want reorder all the rows by means of a permutation vector perm:
a(perm,:);
But if a is a cell array I cannot. I have to copy every single element:
function reorder(XX,perm)
n = size(XX,2);
OO = cell(length(perm),n);
for ii = 1:length(perm)
for jj=1:n
OO{ii,jj} = XX{ii,jj};
end
end
Somebody knows a better technique?
G
G
Check out cellfun.
–Loren
I have created a large cell that holds sign patterns for 4×4 matrices. The matrices stored in the cell are generated by a loop. Is there a way to tell the loop to store only new matrices that are unique and to discard repeated ones?
this is what i have so far:
A=cell (10,10) %for now the size is arbitrary
for i=1:10 j=1:10
a=2;b=2 %create range from M to M
v=a+(ba)*rand(4,1) %create 2 random vectors
w=a+(ba)*rand(1,4)
P=eye(4,4)+v*w %create random matrix P
J=gallery(‘jordbloc’,4,0) %create nilpotent matrix
A1=P*J*inv(P)
ans=(A1>0)
A(i,j)={ans}
end
thank yoU!!!!
Katie
You probably need to consider using unique or ismember when deciding to put an array into a cell. You might get some ideas from looking at the code in
this post.
–Loren
Hello Loren, very good posts you have.
I have this “indexing in cell array problem” that I have been trying to solve for some hours already:
A cell array with lets say 1 row and 3 columns.
– column 1 has a 10×1 cell array of text (labels).
– column 2 has a 10×1 matrix of numbers.
– column 3 is empty and I want to put in it the minimum of column 2 accompanied by its corresponding (same row) text found in column 1.
I have been doing this (for clarity I omit the the assignation so “ans” would take the result):
[myCell{1,1}(find(min(myCell{1,2}))) min(myCell{1,2})]
The problem is it always brings up the minimum and the WRONG label. The label it puts is the first one in column 1 no matter where the minimum is.
Thank you very much.
Roberto
Not sure how you are doing this or if this is even the output you want (because all the labels will be the same since column 2 has only one minimum), but here’s a try.
–Loren
Hello Loren, Thanks for your reply.
Sorry I did not make myself clear. Lets say I am working with this cell:
myCell =
‘Labels’ ‘MEANS’ ‘MIN’
{3×1 cell} [3×1 double] []
{3×1 cell} [3×1 double] []
{3×1 cell} [3×1 double] []
{3×1 cell} [3×1 double] []
A 5×3 cell array, correct?
So I want to extract the minimum from the ‘MEANS’ column for every row of the cell. Also I want that minimum to be placed in the ‘MIN’ column accompanied by the corresponding label from the ‘LABELS’ column. So for example if in the ‘MEANS’ matrix from row 1, element 2 is the minimum, concatenate it with element 2 of the corresponding ‘LABELS’ matrix and place all that in the corresponding ‘MIN’ matrix.
Now do that for every row.
The output (for one row) should be something like:
myCell =
‘Labels’ ‘MEANS’ ‘MIN’
{3×1 cell} [3×1 double] {‘OLS ‘ [1.4000]}
{3×1 cell} [3×1 double] []
{3×1 cell} [3×1 double] []
{3×1 cell} [3×1 double] []
I worked it out with your code like this:
[minimum indx] = min(myCell{2,2})
myCell{2,3} = [myCell{2,1}(indx,1) minimum] ;
but I still don’t understand why this does not work:
myCell{2,3} = [myCell{2,1}(find(min(myCell{2,2}))) min(myCell{2,2})]
THANKS.
Roberto
The problem is with find(min())… piece. You need to break down the pieces here. min returns a scalar for the 3×1 vector and find then finds the first element in that, with is the first 1. That’s why you always get the first label.
–Loren
Hi Loren,
I don’t know whether following has been discussed previously, but, is there a way to preallocate a cell array when the number of matrices in the cell array remain constant but the number of elements in the matrices change? Usually I try following:
A = cell(20,20);
A = cellfun(@(x) zeros(100,1),A,’UniformOutput’,false);
Thereby I allocate a vector with 100 elements for each cell element. Now, the calculations I do may lead to a strong accumulation of values in some matrices while others remain small. Now, how does Matlab handle this? Does it make a difference in the memory allocation, when the matrix in the cell grows to 1000 elements while 10 might be reduced to 0 elements? So far, I do not have the impression that Matlab becomes slow.
Best regards, Wolfgang
Wolfgang
The important thing is to preallocate the cell array itself. Each element in a cell array is effectively a single MATLAB array itself and as look as your cellfun calculation produces each full array for each cell, you should not even need to preallocate the space for each cell array element. Each one will get created via cellfun. You’re now just throwing out your predefined contents and filling them with the new results anyhow.
–Loren
I Loren,
I must say I’ve been learning a lot Matlab since I subscribed to your blog. For that, thanks very much.
I’ve a problem related with cells. I’m trying to read a file witch as several blocks of information and each one of them as its distinctive headerline with the following format
364,1 “04261056.C.2”
I’m using textscan to read the file and the output comes as a cell. Is it possible to read from the cell the value 364 into an array?
Thanks
Joao,
If I understand your question correctly, you have either one or more lines of data like this:
364,1 “04261056.C.2”
364,1 “04261056.C.2”
and you may be reading them like this:
C = textscan(fid,’%d%d%q’, ‘delimiter’, ‘,’)
The results would come out in a cell array like this:
[2×1 int32] [2×1 int32] {2×1 cell}
C{1} is in fact an array of numbers and can be treated as any other array of numbers,
e.g.
>> Array = zeros(1,10)
Array =
0 0 0 0 0 0 0 0 0 0
>> Array(1:2) = C{1}
Array =
364 364 0 0 0 0 0 0 0 0
Hope this helps.
Vadim
Loren, How do convert from nested {{‘a’,’b’},{‘c’},{‘d’}} to flat {‘a’,’b’,’c’,’d’}?
Hi!
Interesting blog.
I want to make a function that prints a text file from a cell with different content. I want it to be flexible, so that I can input any type of cell array.
Is there a way to find out the content in a cell before performing any operations on it. I will give you an example. My cell array contains [Num 1600×1] [String 1600×16] [Num 1600×1] [String 1600×1].
I want to go through the cell, column by column and if it is numeric, perform ‘cell2mat’ and if it is a string perform ‘char’. I don’t know in advance what is in each column.
Thanks!
Ebbe
Ebbe
If you *know* that each column is homogeneous, you could do something like this.
to find the content types for each column. Then you can do what you want from that information.
–Loren
Thanks a lot!
I had to set ‘UniformOutput’ to false:
colContents = cellfun(@(x) class(x(1)), A,’UniformOutput’,false);
Then it worked!
Thanks again!
Ebbe
Hi
I have a small problem. I just started using cell arrays and I’m just lost.
I have an array P1 for which I want to do the following
P1 = [ 2 3 4 0
5 8 0 0
2 3 1 1];
K = P1(:,4)==0 & P1(:,3)~=0;
Z = 1:size(P1,1);
I = Z(K);
P1((P1(:,3)==0  P1(:,4)~=0),:)=[];
so i’ll get
I = 1
P1 = [ 2 3 4 0 ]
and now I have 20 arrays like P1 but different sizes, so I can build a 3 dimensional cell array
P = {P1 P2 P3 …}
is there any way to use indices to perform the same calculations on every P?
Thanks
Marc
Marc
I don’t see where you have all the arrays to start. But if you put the initial arrays into a cell array, you can use cellfun to do your calculations and place the outputs into a cell array.
–Loren
Loren
Thank you so much for the response.
My real stat cell array is
cell 1,1 [69881×13 duble]
cell 1,2 [70160×13 duble]
cell 1,3 [69555×13 duble]
I’ll try to use the cellfun.
Marc
Hi Loren,
I am impressed with your answers to the problems on this topic and hope you can help me with a problem I have been struggling with for some time now.
I have a function that evaluates a given function handle (fHandle) and provides some extra output. At some point I evaluate the function handle
The problem is that the function handle should return a cell array with arrays of more than two dimensions, but it only returns arrays of two dimensions. If I run the following
a and c are 100 X 100 and b is 100 X 100 X 5 as they should be; in my first example temp{1}, temp{2} and temp{3} are all 100 X 100, while temp{2} should also be 100 X 100 X 5 as is b.
It is not possible for me to use [a b c] as different function handles have different number of output arguments.
Thanks in advance
Arco
I don’t understand your code, esp. the righthand side being enclosed in {}. If you can post the SMALLEST amount of code to reproduce the situation, that would be helpful. If it’s really long, I recommend you contact support (link on the side of the page).
–Loren
Loren,
I have a large cell array that I initialized using the cell(m,n) command. Will Matlab need to reallocate memory for the entire array each time I change or add an element?
Thanks,
Scott
Scott
In this case, there are 2 ways in which MATLAB may have to allocate/reallocate memory. 1) if you change teh size of the cell array itself, a reallocation will take place, and 2) MATLAB will allocate memory for each element you assign to. Currently all the cells are empty.
–Loren
I have the same problem to solve, couldn’t find any solution with cellfun, just with nested loop (forend) for every cell nesting.
Oleg and Wei
There is no good way that I know of. You’d need to write a function that would keep going through levels of a cell array until no more cells are found.
–Loren
I feared that would be the answer. That means a good opportunity to write a “nest2flat” function. If interested, as soon as i write it, i’ll make it available on filesharing.
To flatten
the simplest command is
but it fails to flatten more complex cell arrays/matrices like
I wrote a function which deals with any type of nested cells. If interested look for nested cell in the file exchange.
Oleg
Oleg – this is actually a fairly simple exercise in cellfun recursion:
This works very quickly, for any type of input (cell/noncell), and any type of data (numeric/strings/…).
Yair Altman
To Yair:
i discovered the recursive method right after i submitted my function. Bruno Luong exposed the same method as a comment to my function.
Thanks again.
Hello Loren and thanks for your blog.
It gives me much insight and inspiration.
Please some more attention to the “decelling’, (AKA “decellifying” ala Altman).
It really bothers me when trying to enjoy the sopowerful feature of cell arrays.
Is there a simple way to achieve this task:
Such cell arrays, with row label or title string, are most valuable when outputing the results by the MATLAB rptgen, or even with MSEXCEl, which can handle nonenested cells.
TIA
Shlomi
Hi Loren,
I’m fairly new to MATLAB programming and I am having issues with this whole cell indexing thing.
Let me give you a basic example of what I have been up since midnight trying to figure out.
For the following bit of code:
x = 0:2:10;
[n{1:6}] = x(1:6)
why is it not bringing out values for n1, n2, n3 etc and assigning to them the corresponding values of x1,1, x1,2, x1,3….
I keep on getting errors saying “Comma separated list expansion has cell syntax for an array that
is not a cell.”
I’m totally stumped!
– Kemi
Kemi
The right hand side of your expression is just a vector, a single entity, not a cell array. So it can’t get split up to distribute to the left hand side. Instead use mat2cell or num2cell.
is probably the easiest way for this example.
–Loren
I am not able to read image file because of cell array. I want to convert it to string. Please email me its solution.
Prashant
Change your last line to get the filename into a character array by indexing using curly braces.
–Loren
Hi Loren,
I’m having trouble to remove empty vectors within cell arrays. Each cell array contains of a different number of vectors of different lengths. I have identified those vectors that contains too little data and set those to empty using ‘[]’. Now I would like to remove those but I don’t know how, any ideas?
For instance:
ve_prim{16,30}
ans =
[17×1 double] [] [] [120×1 double] []
I have also tried to set the vectors that are too short to ‘NaN’ but the same problem, I can’t remove them.
Regards,
Maria
Maria
Something like this should work.
–Loren
Loren,
I believe this question should still be related to cell arrays. It’s driving me nuts. I’m able to display my variable values to command window, but fprintf only works for the first value, the others come out blank.
To illustrate the problem consider the following:
>> Chi
Chi =
1259×1 struct array with fields:
strain
genotype
parent
type
researcher
mutations
>> Chi(2).strain
ans =
c11002
>> Chi(2).genotype
ans =
DphoP81
>> Chi(2).parent
ans =
c3761
So far so good.
>> fprintf(‘%s \n’,Chi(2).strain)
c11002
>> fprintf(‘%s \n’,Chi(2).genotype)
>> fprintf(‘%s \n’,Chi(2).parent)
This is just not logical to me, especially since “strain” and “parent” are formatted the exact same way. I’m at a loss as to what to try next.
– greg
Greg
It works for me. I suggest you contact technical support (link on right). Be sure to give them all your details, MATLAB version, etc.
–Loren
Loren,
Do you know of any differences in how the ‘disp’ and ‘fprintf’ commands treat strings/structures?
I thought I might have an input file with strange special characters so I created a simple text file from scratch and I’m still seeing ‘disp’ print things that ‘fprintf’ can’t. Perhaps the %s formatting treats cell structures differently?
Here’s a simpler command window output that shows the issue quite distinctly:
>> test=Chi(record_number).parent
test =
c1
>> length(test)
ans =
3
>> fprintf(‘[%s] \n’,test)
[]
>> disp(test)
c1
So I have this “thing” called test. I think it’s a string. Matlab shows it to have a length of 3 and Matlab ‘disp’ works just fine and says it’s value is ” c1″. Yet when I give this string to fprintf nothing happens.
I have a feeling this is one of those strange things in Matlab where I just need to enclose it in “[]” or “{}” or “()” and it would work. But I’ve tried many many permutations and it’s still a mystery.
If you have no idea why this is happening I doubt tech support will either and I will probably rewrite all my code in Perl :(.
– Greg
Greg
test is a string, but why is it length 3? I wonder if you have some funky character in it. Try something like this:
double(test)
to see what’s inside to see if some of the elements are nonprinting characters that might mess up fprintf.
–Loren
Loren,
It looks like the first character was a “NULL”:
i.e.
>> double(test)
ans =
0 99 49
I ended up changing the structure I was loading my data into, and also changing the fprintf statements from this:
fprintf(‘%s \n’,Chi(2).genotype)
to this:
fprintf(‘%s \n’,Chi.genotype{2})
and got everything to work.
I love the simplicity of Matlab, but when it comes to indexing I always seem to get myself into a nest of bugs!
Thanks for your help!
– Greg
Is there any functionals for ‘{:}’ operator? I’m trying to expand all the cells and vertcat them inside an anonymous function handle to be used in structfun(), so I don’t have the luxury of generating a cell ‘C’ then do vertcat(C{:}).
Thanks.
Hoi Wong
There is no functional form for ‘{:}’. You have to form the cell array and then apply it, requiring 2 steps.
–Loren
hello
I am new to matlab… I can read my data into matlab but it in single column, how to split it into four array/element such that it read data 1 2 3 4 1 2 3 4 …………… 1 2 3 4
1 to one array 2 another array and so on.
Nash
Instead of separate arrays, you are better off placing the data in the columns of an array or into a cell array. Check out the function reshape and reading the Getting Started with MATLAB part of the documentation.
–loren
After the above simple example i want to check if the contents of cell array I are present in the cell array total. I cannot user intersect as it doesn’t work. I cannot use equal or anything like that. How can i compare the contents of a cell array to see if another cell array is present. I want to modify the contents of I and add them to total=[I;II] again, but before i do that I need to check if the specific row already exists inside the total cell array.
May i thank you in advance for your help.
Regards
Daf
You will need to run a loop or use cellfun to do comparisons for elements in total to see if they contain A. isequal will help.
–Loren
Let me check i understand this correctly: I am supposed to use the loop to do a row by row comparison, right?
but when i put
or
i get
??? Undefined function or method ‘isqual’ for input arguments of type ‘cell’.
how can i use the function isequal to do the comparison?
Daf
It’s isequal, not isqual.
–Loren
Hello Loren
How would you characterize the difference between
I can see that e is a cell with empty matrix and f is an empty cell, but in practical terms, can you think of some examples when it would it make a difference? Thank you. Matteo
Matteo
e is a 1×1 cell whose first element is an empty array. f is an empty cell array (length = 0).
Sure it can make a huge difference. If you have a cell array with contents the length of something else, you need to get the cell’s length correct. If you care about the length, but have perhaps a default somewhere, you might represent that with an empty array within a cell array.
–Loren
I’m using uigetfile with MultiSelect, and it works fine if the user selects multiple files:
But if the user selects only one file I get an error:
??? Cell contents reference from a noncell array object.
How can I work if the user selects only one file?
Thanks
Don
I’m not near a place where I can try it, but does uigetfile return a string if it’s just a single output? If so, you can’t do cell indexing for just one result. But I am not sure…
–Loren
Loren,
Here’s your documentation:
uigetfile(…,’MultiSelect’,selectmode) sets the multiselect mode to specify if multiple file selection is enabled for the uigetfile dialog. Valid values for selectmode are ‘on’ and ‘off’ (default). If ‘MultiSelect’ is ‘on’ and the user selects more than one file in the dialog box, then FileName is a cell array of strings, each of which represents the name of a selected file. Filenames in the cell array are in the sort order native to your platform. Because multiple selections are always in the same directory, PathName is always a string that represents a single directory.
When MultiSelect is ‘on’, if the user selects one file, uigetfile returns the file name in a string. If the user selects more than one file, it returns a cell array of strings. I’m normally expecting him to select more than one file, and the first thing I do is sort the cell array, so the files are processed in order. But sorting the file name of single file doesn’t work. When MultiSelect is on, it would be nice if uigetfile returned a cell array of strings regardless the number of files selected. Having it return a string when MultiSelect is off is fine. Even checking the length of the return file name doesn’t work. One case returns the length of the file name, the other returns the number of files. So I’m not even sure how to detect the number of files the user selected.
Don
You can check using the isa function (isa with ‘cell’ or ‘char’ to check the class).
–Loren
That gets around the problem. If uigetfile comes back with a string, I change it into a cell array of strings with one element. Otherwise I sort the cell array uigetfile returns.
I have some cell arrays in a struct field, like
Each mean , min and max holds just a single value.
But dat itself is 2D (twodimensional). I could have simply used a 3D array. But I didn’t, because I like the feature of having a mnemonic to know what each index means, instead of having to memorise “k=3 in the third dimension corresponds to maximum”.
In any case, eventually I want to be able to graph (i.e. plot) this data. Which seems only to be possible by transferring it into noncell arrays, i.e. matrices, or (in this case) vectors.
At first I couldn’t find a way of doing it without iterating through every index of dat . Like this:
I tried
but this gives a 1D cell array, rather than a vector.
Eventually I discovered, purely by accident and a lot of trialanderror, that the following works
The inclusion of jBig and its was peculiar to this circumstance only, where I had stopped the code before completion.
But note that
returns 1D vectors, which is NOT the intended result.
—DIV
P.S. You need a command to produce _inline_ formatting of text as code.
uigetfile with the ‘MultiSelect’ on, When users pick one file it returns a string, when users pick more than one file, it returns a cell array, return cell arry for both case will make life easier, because I don’t have to use different ways to process the return file names.
[name_all, pathname, FilterIndex] = uigetfile({‘*.jpg’,’All Image Files’;…
‘*.*’,’All Files’ },’Select Images to Execute’,…
‘C:\’,’MultiSelect’, ‘on’)
bt
bt
I agree with you that uigetfile is harder to use in multiselect form because of the possibility of the singleton. Can you please place this suggestion as an enhancement request to support? There is a link on the right of the blog to take you to the request site. Thanks.
–Loren
I have a matrix 10×1 size. I want to wrt it in a cell array of 11×5 size
I am typing following command,
GlobalMinMax{1:10,1} = Min_Min(1:10,1);
but it gives an error “??? The right hand side of this assignment has too few values to satisfy the left hand side.”
I have tried all following possible variations in Min_Min Indexing:
GlobalMinMax{2:11,2} = Min_Min(1:10,1);
GlobalMinMax{2:11,2} = Min_Min(:,1);
GlobalMinMax{2:11,2} = Min_Min(:);
also tried num2cell; num2str and mat2cell functions:
GlobalMinMax{2:11,2} = num2cell(Min_Min(1:10,1));
GlobalMinMax{2:11,2} = num2str(Min_Min(1:10,1));
GlobalMinMax{2:11,2} = mat2cell(Min_Min(1:10,1));
but it gives the same error. Kindly help
vandita
vandita
You can only use a scalar on the left hand side when using {} indexing. {} gets the contains from the cell. If you want more on the left hand side, you need to use the notion of commmaseparated list and enclose the results in []. But I don’t think that’s what you want in your case anyhow.
I am guessing you want something like this
[GlobalMinMax{1:10,1}] = deal(num2cell(Min_Min(1:10,1));
–Loren
Hi Loren,
I’m a fairly new Matlab user and I have a problem which involves combining cell values.
for example:
M=
1 2 3
4 5 6
7 8 9
a 3×3 array
I wanna combine the values of the 1st row into one cell, e.g:
M=
123
456
789
a 3×1 array, is it possible? Because I have a cell array of over 8000 values and doing them manually would kill my eyes. :)
thank you!
Adriel
Perhaps convert the cells to strings, concatenate the rows of strings, and then reconvert to numbers.
–Loren
Thank you Loren! :D
hello Loren,
I am new to Matlab. And I have this GPS data that I need to process. I was able to filter the rows that are of my interest. Each row has multiple data fields but it is all showing up in one cell. I have been looking for some help on the internet but all the help I found was on merge the columns not on isolating fields in separate columns. Below is a little piece of code that I found on the internet and I have modified it to fit my requirements.
fid = fopen(filename);
start_string = ‘$GPGGA’;
headerlines = 0;
line_no = 1;
while feof(fid) == 0
tline{line_no} = fgetl(fid);
line_no = line_no+1;
end
index = strmatch(start_string,tline(headerlines+1:length(tline)))+headerlines;
S = tline(index);
S = S’;
This code helps me filter all the GPGGA data.
‘$GPGGA,151114.400,4050.4609,N,08933.3798,W,1,10,1.09,145.7,M,34.0,M,,*51’
So all of this stuff is showing in a single cell.
Is there anyway I can separate these comma separated fields in separate columns which will make it easier for me to run some processing tools on it.
Salman
You may be better off using one of the text readers if your data are in a text file, e.g., textscan.
Independently, if you read the data in as test, sscanf to get the data from a string into whatever fields you want.
–Loren
I have a question about content indexing:
a(1:3) = {[1 2 3)} % setting up the cell array
a{1:3} will give a{1}, a{2}, a{3}
However a{1:3}(1) will not give a{1}(1), a{2}(1), a{3}(1) but results in an error “??? Bad cell reference operation.”
That doesn’t make sense, or does it?
Is there a quick way to extract specified elements of multiple cells with one line of code? Or at least without a for loop? I want to extract the first element of each cell entry into a vector.
Thanks!
Johann
You can only get specific contents from a single cell in a cell array at a time. The reason is that there is no guarantee that the first element in each cell, for example, even exists (could be empty) or are the same datatypes.
You could try using cellfun or arrayfun, but I believe under the hood they would each be going through a loop, which you can easily do yourself as well. If you are looking for your code to avoid the loop, then you can hide it, as I say, with cellfun or arrayfun.
–Loren
Is it possible to access elements of a cell array without a for loop in this instance?
I’m intersted in finding a way of returning the n’th element of each cell. For example
returns 2
returns 5
returns an error
Zach
You can use cellfun for this (though it has a for loop inside).
–Loren
Dear loren,
I am facing storing different sizes of array as a cell array and here is my dummy code for your review.
let say, I had
tmp1 = [8×1 double];
tmp2 = [123×1 double];
.
.
.
tmpN1 = [56×1 double];
tmpN = [3×1 double];
I want to save all these arrays in one cell array or one array how should I do?
Thanks and best regards
Kyaw
Kyaw
First you should never name arrays like that. As you are finding, it is very difficult to manipulate them.
Instead start with either a struct or a cell array. Let’s say you use a struct. Then you can do something like this
of for a cell array:
etc.
–Loren
Dear Loren,
Thank you for your prompt reply and my tmp cell array is dynamic length with dynamic size depend on the user mouse click on the image.
e.g
tmp1 = [8×1 double];
tmp2 = [12×1 double];
tmp3 = [3×1 double];
tmp4 = [30×1 double];
then I want to have all these sum of cell arrays as one array finally like below.
% Here sum of all cell arrays from the beginning to end
tmp = [53×1 double];
So,I didn’t know the final length then how should I set the dynamic end point in the structure.
Pls advise me and I really appreciate your help.
Thanks and best regards
Kyaw
Kyaw
Again, with your original arrays in separate variables, there is nothing special you can do. It would be ok if they instead were fields of structs or in a cell array. Given the concatenation you want to do, putting the data into a cell array makes the most sense. If you do have the cell array C, size 1xN, to concatenate all the values into one array is easy, provided the values are commensurate types and sizes (does NOT require them to be the same sizes). But you would want the arrays you put into cells to be row vectors if possible to avoid more required manipulation.
newArray = [C{:}];
What this does is make a comma separated list of the array values in each cell, e.g., C{1},C{2},…,C{N} and then places these into a regular array because of the surrounding square brackets. newArray then is:
[values in C(2),values in C(2),…] or
[ 1×8, 1x 12, 1x 3, 1×30] — or length 53
There is good user documentation on this. I suggest you check out the doc and look for commaseparated lists.
–Loren
Hi Loren,
This is a really simple question, hopefully you can help..
I have a cell array, where each cell contains a numeric vector of varying length, and just want to multiply everything by a constant. How?
Thanks,
Hannah
Hannah
Take a look at cellfun.
–Loren
Hi Loren
would you help me in converting a cell array into a numeric array
in my project i am dividing an image into blocks using mat2cell and make some analysis on each block
i need to convert each block into a numeric array
Thank you in advance
Yasmine
Check out the function cell2mat: http://www.mathworks.com/help/techdoc/ref/cell2mat.html
–Loren
So I’m just getting used to using cell arrays and from the matlab help docs it says I should use the function importdata. The file I am inporting to matlab has the following data types:
Ushout, Uchar, Short, Float
All my data is hex formatted and here is what the first few lines look like:
Date: Mon Dec 05 13:38:15 2011
13:38:16 90 EB 30 00 BA 01 E6 01 B6 02 35 00 3E 0B E6 05 EB
13:38:17 90 EB 30 00 BA 01 E7 01 A2 02 21 00 3E 0B FF 05 EB
13:38:18 90 EB 30 00 BA 01 E8 01 B6 02 21 00 3E 0B E6 05 00
etc.
So once I import the data into matlab using importdata I get a Nx1 cell array with N being the number of lines in the input data file. How do I index to each individual character in each line. I need to do this so I can concatenate multiple individual characters.
After doing the concatenate I will then convert the concatenated hex strings?? to decimal.
Thnaks,
willie
Hi Willie,
importdata might not be your best option. textscan MIGHT be more appropriate, I am not sure.
But to answer your question about indexing into cells, here’s the way.
If C is your Nx1 cell, to get the mth character from the nth line, do the following C{n}(m) – curly braces first to get the contents of the nth row, then smooth parens to index into that array.
–Loren
i can’t seem to extract the first entry of each cell into a new variable.
right now i’m doing it (with no success) as follows:
though it seems to create it properly, it produces the error:
“conversion to double from cell is not possible”
thank you,
eva
Eva
I don’t have access to MATLAB now but I don’t think you can do that in a vectorized way. Without seeing your code, I am not sure what you’ve actually tried. I recommend a for loop, first preallocating the output or using something like arrayfun. If you can’t get either of those to work, please contact technical support.
–Loren