How to NOT share variable with nested function?
Show older comments
Hello,
I made a big code in a separate m.file, this code includes functions. I then want to make a function out of this big code, but, by doig so, i create nested functions and, as those function share the sames variable names, nothing is working properly anymore.
Is there a way to precise that the nested function inside a function should not share variables with the main function and with each other?
Thank you for your help!
2 Comments
@Thomas Fournier: By definition, the scope of nested functions includes all variables from their parent function/s:
If you need to use nested functions, then you will need to rename those variables.
But I suspect (due to that the code originally worked "in a separate m.file") that you do not need nested functions at all, and you can probably simply define them as local functions together with one main function at the start of the file, thus trivially avoiding the whole problem:
Thomas Fournier
on 12 Aug 2021
Accepted Answer
More Answers (2)
If you declare function or variable inside nested function it rewrites itself. There is no option for mistake
function main
a = 2;
b = 3;
a + b
function nest1
a = 5;
a + b
end
a + b
end
4 Comments
@darova: with your example the code in the nested function never runs, because you do not call the nested function. Simply placing some code after the nested function definition is not equivalent to actually calling that nested function.
Try this instead (we can also clearly see that the shared variable in the MAIN function has changed):
main()
function main
a = 2;
b = 3;
a + b
nest1() % <---- call the nested function!
a + b
function nest1
a = 5;
a + b
end
end
darova
on 12 Aug 2021
Indeed. But why a value in main is changed?
ans = 5
ans = 8
ans = 8
I expected
ans = 5
ans = 8
ans = 5
Walter Roberson
on 12 Aug 2021
The line
a = 5;
does not make a into a local variable inside the nested function: instead it writes to the shared variable.
"But why a value in main is changed?"
Shared variables are explained in the MATLAB documentation:
Jeff Miller
on 11 Aug 2021
0 votes
It sounds like your "big code" is a script rather than a function, but now you want to make a function out of it.
I suggest you remove the functions from the "big code" script and put them in separate files. Then make "big code" into a function, but these other functions will no longer be nested so each will have its own separate variables.
Categories
Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!