Update field value in structures?

조회 수: 3 (최근 30일)
Najmeh Eskandari
Najmeh Eskandari 2019년 2월 10일
댓글: Walter Roberson 2019년 2월 10일
Hi.
I have structure L with field L0. L0 has two fields:H0 and H1.
H0=struct('h',[0,0],'Q_centroids',[-5,0,5,0],'Q_actions',[15,7,10],'Q_table',[0]);
H1=struct('h',[0,2],'Q_centroids',[1,0,pi/2,0],'Q_actions',[2,7,8],'Q_table',[2]);
L0=struct('H0',H0,'H1',H1);
L=struct('L0',L0);
relevant_L=L.L0;
relevant_L.H0.Q_centroids=[-pi/2,0,pi/2,0;1 5 4 2];
I want to update H0 and then save it in L. so i load L0(relevant_L=L.L0) then update it through the last line but new strcture is created(name:relevant_L).
i know we can do this by:
L.L0.H0.Q_centrids
but i want to change Q_centroids first by load L.L0 in another variable(relevant_L) and then change it.
Is it possible?
Thanks.

채택된 답변

Walter Roberson
Walter Roberson 2019년 2월 10일
If the question is whether it is possible to create an "alias" to something inside a structure, such that assigning to the name will have the effect of changing the part inside the structure -- if that is the question, then the answer is NO, that cannot be done in MATLAB with struct
That said, something that would look like that can be done in MATLAB. It would require that L0 would be an object of a class derived from handle and that the class had a H0 property. In that particular configuration, then updating relevant_L.H0 would have the effect of updating L.L0.H0 .
  댓글 수: 2
Najmeh Eskandari
Najmeh Eskandari 2019년 2월 10일
Ok.
i use fieldname to find fields name in L:
H0=struct('h',[0,0],'Q_centroids',[-5,0,5,0],'Q_actions',[15,7,10],'Q_table',[0]);
H1=struct('h',[0,2],'Q_centroids',[1,0,pi/2,0],'Q_actions',[2,7,8],'Q_table',[2]);
L0=struct('H0',H0,'H1',H1);
L=struct('L0',L0);
FieldNames=fieldnames(L);
FieldNames={'L0'}.
Now can i for example define
a={'L0'};
then use
L.(a{1});
?
Walter Roberson
Walter Roberson 2019년 2월 10일
Yes, you can use
STRUCTURENAME.(CHARACTER_VECTOR)
to access the field in STRUCTURENAME that the CHARACTER_VECTOR evaluates to. Your example of A={'L0'} and L.(a{1}) is fine, and is the same as L.('L0') which will evaluate as if you had used L.L0

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

추가 답변 (0개)

카테고리

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