How to create a cell array with struct elements?

118 次查看(过去 30 天)
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.

采纳的回答

Walter Roberson
Walter Roberson 2015-11-8
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.

更多回答(1 个)

Stephen23
Stephen23 2015-11-8
编辑:Stephen23 2015-11-8
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 个评论
Nikos Pitsianis
Nikos Pitsianis 2020-3-21
编辑:Nikos Pitsianis 2020-3-21
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 2020-3-21
编辑:Stephen23 2020-3-21
"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',[]);

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by