I have two functions in matlab, which roughly look like this
function f1()
setup_callback(@f2);
a = 1;
evaluate_callback();
end
function f2()
...
end
where evaluate_callback is an external library function which calls f2.
I want to be able to read the current value of a from inside f2. Is there some way to achieve this without using globals?
Make f2
a nested function inside f1
:
function f1()
setup_callback(@f2);
a = 1;
evaluate_callback();
function f2()
%# you can access a here
disp(a)
end
end
Nested functions will provide the scoping you want. Note that there's no other way to call the f2 callback function than either from inside f1, or via the function handle. So f1 could return the @f2
handle, and other functions at global scope could call it that way.
function f1()
setup_callback(@f2);
a = 1;
evaluate_callback();
function f2()
% refer to a
...
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With