How to create a cell array with struct elements?

112 views (last 30 days)
I want to create a 2x7 cell array. Each element of the cell will be an empty structure with a field name of "myfield". I can do it using nested loops:
for i=1:2
for j=1:7
mycell{i,j} = struct('myfield',[])
end
end
Is there any way to avoid the loops? It looks ugly in my code.

Accepted Answer

Walter Roberson
Walter Roberson on 8 Nov 2015
repmat({struct('myfield',{})}, 2, 7)
Note the correction of struct('myfield',[]) to struct('myfield',{}). The version you had, with [], is for a 1 x 1 struct with a field that is initialized to []. The version with {}, creates a 0 x 0 struct with the field defined in its template but with no content. An "empty structure" should have have 0 as one of its dimensions or else it is not actually empty.

More Answers (1)

Stephen23
Stephen23 on 8 Nov 2015
Edited: Stephen23 on 8 Nov 2015
Rather than putting lots of separate structures into a cell array, you should consider simply using a non-scalar structure, which would be much more efficient use of memory, and has very neat syntax to access the data. Although many beginners think that structures must be scalar they can in fact be any sized array, and so you can access them using indexing, just like you would with your cell array. Try this:
>> X(3).field = [3,NaN];
>> X(2).field = 2;
>> X(1).field = [-Inf,1];
>> X.field
ans =
-Inf 1
ans =
2
ans =
3 NaN
>> [X.field]
ans =
-Inf 1 2 3 NaN
>> X(2).field
ans =
2
And you can even preallocate the entire non-scalar structure very simply:
>> Y = struct('field',cell(2,3))
Y =
2x3 struct array with fields:
field
and then access these fields really easily:
>> Y(2,3).field = 'blah';
>> Y(1,1).field = 'hello';
>> Y(1,2).field = 'world';
>> {Y.field}
ans =
'hello' [] 'world' [] [] 'blah'
  2 Comments
Nikos Pitsianis
Nikos Pitsianis on 21 Mar 2020
Edited: Nikos Pitsianis on 21 Mar 2020
How can I preallocate an array of struct with more fields?
Say an 10x1 array of point structures with fields x', 'y' and 'z'?
Stephen23
Stephen23 on 21 Mar 2020
Edited: Stephen23 on 21 Mar 2020
"How can I preallocate an array of struct with more fields?"
Here are three ways:
1- repmat a scalar array:
S = repmat(struct('x',[],'y',[],'z',[]),10,1);
2- non-scalar cell array with struct:
S = struct('x',[],'y',[],'z',cell(10,1));
3- Assuming that the variable does not exist in the workspace, then allocate to its tenth element (the variable will be created and the rest of the elements will be implicitly filled with default values (empty array in case of structure fields), just like you can do with any other array class):
S(10,1) = struct('x',[],'y',[],'z',[]);

Sign in to comment.

Categories

Find more on Structures 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!