MATLAB: Why evalin(‘caller’, ‘evalin(”caller”, ”a”)’) works in a stack of script. but not a stack of functions

evalinrecursive evalin

Suppose three m files of script:
test1.m
a=1;
test2;
test2.m
b=2;
test3;
bb
test3.m
c=3;
evalin('caller', 'evalin(''caller'', ''a'')')
assignin('caller','bb','bbbhahaha');
Then test1 runs OK and shows the value of a;
However, if these scripts are headed with "function *" then error appeared:
Error using evalin Undefined function or variable 'a'.
Error in test3 (line 3) evalin('caller','evalin(''caller'',''a'')');
Error in test2 (line 3) test3;
Error in test1 (line 3) test2;

Best Answer

While using functions is surely the best answer, the actual question concerned scripts. Then you do not have to call evalin at all but you can access the variables directly. This is the only benefit of scripts:
% file: test1.m
a=1;
test2;
% file: test2.m
b=2;
test3;
disp(bb)
% file: test3.m
c=3;
bb = 'bbbhahaha';
disp(a)
Works. So simply omit the evalin call. Or restructure the code to use functions and inputs/outputs to get a clean and efficient code.