Abbreviate acces to struct fields

조회 수: 3 (최근 30일)
Rafael Kübler
Rafael Kübler 2017년 7월 6일
편집: Jan 2017년 7월 6일
Hello everyone,
i often need to acces a struct field like
sturcture.firstLevel.secondLevel.thirdLevel = 1
Now my question is: Is there a way to abbreviate this long code? Something like defining a pointer.
For example:
sThird = pointer(sturcture.firstLevel.secondLevel.thirdLevel)
Whereas from now I could substitute
sThird
for
sturcture.firstLevel.secondLevel.thirdLevel
Is there a way to do this, so my code is to long?
Thank you for your time reading this.
Rafael

채택된 답변

Guillaume
Guillaume 2017년 7월 6일
편집: Guillaume 2017년 7월 6일
With structures, no it's not possible. Matlab does not support pointers/reference to variables. The workaround is to define a new variable, use that variable to do whatever you wanted to do, and then reassign that variable back to the structure
sThird = structure.firstLevel.secondLevel.thirdLevel;
%do something with sThird
structure.firstLevel.secondLevel.thirdLevel = sThird;
The only other way would be for the content of that thirdLevel field to be a handle class object that wrap whatever it is you store in there. In my opinion, this would be a waste of time just to offer shorter typing in the editor.
edit: forgot another option, which I also don't think is a good idea, use getfield and setfield:
field = {'firstlevel', 'secondlevel', 'thirdLevel'};
value = getfield(structure, field);
setfield(structure, field, someothervalue);
  댓글 수: 1
Jan
Jan 2017년 7월 6일
편집: Jan 2017년 7월 6일
+1: The first suggestion is perfect. sThird = s.a.b.c creates a shared data copy in Matlab. This means if s.a.b.c is a struct and contains a huge array, the actual data are not duplicated. Therefore this method is fast, even faster than accessing s.a.b.c directly, when it occurres frequently in a loop:
structure.firstLevel.secondLevel.thirdLevel = 17;
tic
for k = 1:1e7
structure.firstLevel.secondLevel.thirdLevel = ...
structure.firstLevel.secondLevel.thirdLevel + m;
end
toc
structure.firstLevel.secondLevel.thirdLevel = 17;
tic
sub2 = structure.firstLevel.secondLevel;
for k = 1:1e7
sub2.thirdLevel = sub2.thirdLevel + m;
end
toc
Elapsed time is 0.053434 seconds.
Elapsed time is 0.036151 seconds.
Well, does not look too impressive for 1e7 iterations.

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

추가 답변 (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