Substruct array disappear when a struc object is assigned

조회 수: 2 (최근 30일)
Luca Di Leta
Luca Di Leta 2016년 4월 10일
댓글: Luca Di Leta 2016년 4월 11일
Hi guys,
I have started to use struct to create nested arrays which will be assigned in a second time , for example:
S = struct( ...
'A', struct( ...
'A_ID', struct( ...
'C', [], ...
'D', [], ...
'E', struct( ...
'EF',[], ...
'EG',[], ...
'EH',[], ...
'EI',[]))));
but when i try to assign the object values, something strange happens, the substructure information disappeares. For examples i assign to the first postion of the object A_ID the value of C = 'test1'
S.A.A_ID(1).C='test1'
and i obtain
S.A.A_ID(1) =
  • C: 'test1'
  • D: []
  • E: [1x1 struct]
now if i assign a new value for C in a new position of A_ID for example
S.A.A_ID(2).C='test2'
i don't obtain
S.A.A_ID(2) =
  • C: 'test2'
  • D: []
  • E: [1x1 struct]
but
S.A.A_ID(2) =
  • C: 'test2'
  • D: []
  • E: []
and i lost all the information contained in the nested struct E !!
i don't really understand why, have someone an idea??
thank's in advance
Luca

채택된 답변

Geoff Hayes
Geoff Hayes 2016년 4월 10일
Luca - the substructure (for the second element) doesn't disappear as it was never there to begin with. Since you are initializing it for the first time with
S.A.A_ID(2).C='test2';
then the D and E will be set with default values of the empty matrix for each. You would need to copy the elements over from S.A.A_ID(1).
Remember, when you initialize your S as above, then
numel(S.A.A_ID)
is just one. There is no second element, and S.A.A_ID is identical/equivalent to S.A.A_ID(1).
  댓글 수: 3
Geoff Hayes
Geoff Hayes 2016년 4월 11일
Luca - if you want to update the kth element of the array, then you should probably check to see if this index is greater than the length of the array and update it accordingly. For example,
if k > length(S.A.A_ID)
for m=length(S.A.A_ID)+1:k
S.A.A_ID(m) = S.A.A_ID(1);
end
end
S.A.A_ID(k).C = 'test2';
We initialize all elements to the master copy and then update the C field for the kth element.
Luca Di Leta
Luca Di Leta 2016년 4월 11일
Hi Geoff! thank you very much for your input, I make now a test and I give you a feedback
Luca

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2016년 4월 10일
You need to assign a copy of the master layout and then change the fields you want changed. MATLAB automatically extends with 0s or empty (or NAt, Not a Time, for datetime arrays) and never automatically copies from templates
  댓글 수: 1
Luca Di Leta
Luca Di Leta 2016년 4월 10일
편집: Luca Di Leta 2016년 4월 10일
Hi Walter, that's no other way to build a dynamic struct array? I could also first set the dimension of my arrays but it's not an elegant solution for struct they no have always the same dimension...

댓글을 달려면 로그인하십시오.

카테고리

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