필터 지우기
필터 지우기

accessing timer UserData fields

조회 수: 11 (최근 30일)
Joris Lambrecht
Joris Lambrecht 2016년 9월 13일
댓글: Walter Roberson 2016년 9월 13일
t=timer;
t.UserData = struct('field1', 'a', 'field2, 'b');
t.UserData.field1
% returns an error:
%inconsistently placed '.' in subscript expression
get(t.UserData, 'field1')
%returns an error:
%Conversion from double to struct not possible
get(get(t, 'UserData'), 'field1')
% returns same error
u = t.UserData;
u.field1 %works fine
Thus I have a workaround but it's kind of clunky: I set a variable to u=t.UserData at the beginning of my timer callback function and then set t.UserData=u at the end of my timercallback function
Why can't these fields be accessed directly?

채택된 답변

Walter Roberson
Walter Roberson 2016년 9월 13일
Interesting, I had never seen that message before.
The work-around is
getfield(t.UserData, 'field1')
  댓글 수: 3
Joris Lambrecht
Joris Lambrecht 2016년 9월 13일
편집: Joris Lambrecht 2016년 9월 13일
Unfortunately, the counter to this does not seem to work. If I want to set the value of the field:
setfield(t.UserData, 'field1', 'c')
returns field: 'c' as expected, but a follow up call to
getfield(t.UserData, 'field1')
returns 'a'
Walter Roberson
Walter Roberson 2016년 9월 13일
t.UserData = setfield(t.UserData, 'field1', 'c')
setfield does not assign to a variable: setfield returns the modified value.
As to why it happens:
MATLAB objects can have properties that are represented as fields in a struct that is marked as being of the appropriate class. If any given property happens to be a struct and the property is directly represented as a struct field, then it can be sub-referenced in the way that would seem natural.
But MATLAB objects can also have properties that are calculated rather than being directly represented, "Dependent" properties. Nearly everything about timers are implemented as Dependent properties, with the code that handles the implementation accessing a java object that is directly stored in a struct. Dependent properties cannot be sub-referenced in the way that would seem natural. When I look at the implementation of timer.m it appears to me that the Dependent properties might be created as dynamic properties; I do not know the backing implementation for those.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by