Scope of variables passed to function handles?

2 views (last 30 days)
Dehuan
Dehuan on 16 Dec 2014
Commented: Dehuan on 16 Dec 2014
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

Accepted Answer

matt dash
matt dash on 16 Dec 2014
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 Comments
Dehuan
Dehuan on 16 Dec 2014
Thanks guys.
This is actually a very neat feature.
It makes dependency-inject and functional programming a lot simpler.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!