How to create a cell array with struct elements?

조회 수: 108 (최근 30일)
John
John 2015년 11월 8일
편집: Stephen23 2020년 3월 21일
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