I am a little confused about the variables' scope in a nested function in MATLAB.
- As nested function help docs explains: vaiable remains local to the nested function.
function main
nestedfun1
nestedfun2
function nestedfun1
x = 1;
end
function nestedfun2
x = 2;
end
save('maindata')
end
Does 'remains local' mean variables are deleted after calling nested function? Or keeping them in nested local workspace?
My opinion: main function calls nestedfun1 and nestfun2, but variables are local to nested function, so after these 2 nested functions are called, variable x is removed (deleted), so maindata.mat is empty, right?
- Sharing variables between parent and nested functions.
function main2
nestfun2
function nestfun2
x = 5;
end
x = x + 1;
end
main2 could be run successfully, but what I don't understand is:
a) call of nestfun2 is before x=x+1, why main function could be run? There is no define variable x when calling nestfun2.
b) Which line does MATLAB parse the function to see what variable will be created? x=5 or x=x+1?
x=5 is earlier but it's in nested function.
c) Variable remains local, after calls nestfun2, why variable x=5 could be transferred to x=x+1?
d) If x=x+1 is deleted, main2 could also be run successfully. But if it's changed to just x, main2 produces an error (“Identifier 'x' is not a function or a shared variable”), why?