필터 지우기
필터 지우기

Scope of variables passed to function handles?

조회 수: 2 (최근 30일)
Dehuan
Dehuan 2014년 12월 16일
댓글: Dehuan 2014년 12월 16일
Hi, everyone,
I want to ask about the non-input variables in function handles.
For example, following code returns h(1)=2.
b=1;
h=@(a)a+b;
clear b;
display(sprintf('h(1)=%d', h(1)));
Is this kind of usage safe and correct?
Dehuan

채택된 답변

matt dash
matt dash 2014년 12월 16일
As far as i know, yes this is safe and correct. Any non-input variables pass their values to the function at the time the function handle was created. Subsequent changes to or clearing of those variables has no effect on the function.
  댓글 수: 2
Adam
Adam 2014년 12월 16일
Yes, this is correct. It is also why passing the handles structure, for example, in a GUIDE-based file to a callback is not a good idea, because a copy of the structure at the exact time the callback is set is hard-coded into the callback, irrespective of when it is called.
Dehuan
Dehuan 2014년 12월 16일
Thanks guys.
This is actually a very neat feature.
It makes dependency-inject and functional programming a lot simpler.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by