Split a variable between two functions in MATLAB?

I have two functions in matlab that look something like

function f1() setup_callback(@f2); a = 1; evaluate_callback(); end function f2() ... end 

where valu_callback is an external library function that calls f2.

I want to be able to read the current value of a from inside f2. Is there a way to achieve this without using global variables?

+4
source share
2 answers

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 
+9
source

Nested functions will provide the required scope definition. Note that there is no other way to call the f2 callback function than either from within f1 or through the function descriptor. That way, f1 can return the @f2 handle, and other functions in the global scope can call it that way.

 function f1() setup_callback(@f2); a = 1; evaluate_callback(); function f2() % refer to a ... end end 
+2
source

Source: https://habr.com/ru/post/1416414/


All Articles