What is the cause of this weird phenomenon with symbolic variables and nested function?
2 次查看(过去 30 天)
显示 更早的评论
This makes no sense to me.
This script returns the symbolic variable 'symb' as expected
funct1
function funct1
syms symb
disp(symb)
end
Adding a nested function causes syms to return an error, even if the second function isn't called
funct1
function funct1
syms symb
disp(symb)
function funct2
%nothing
end
end
Error using assignin
Attempt to add "symb" to a static workspace.
See Variables in Nested and Anonymous Functions.
Error in syms (line 257)
assignin('caller', x, xsym);
Error in weird>funct1 (line 5)
syms symb
Error in weird (line 1)
funct1
However, if you assign a value to symb anywhere within the parent function, the error is avoided. Even if the assignment of symb is never reached by the function.
funct1
function funct1
syms symb
disp(symb)
function funct2
%nothing
end
return
symb=0;
end
Why? What is going on here? Why does adding a nested function to a function prevent you from creating symbolic variables, and why does defining the variable in an unreachable part of the parent function make it possible again?
0 个评论
采纳的回答
Walter Roberson
2020-1-29
编辑:Walter Roberson
2023-2-8
Normally if you have an end matching a function statement then the workspace is static and nothing can be added to it dynamically by assignin('caller') such as is used by syms. syms is not a keyword: it is an ordinary function that uses assignin to create the variables.
It appears that the case of a function inside a script might be an exception that is not considered static, unless the function has a nested function.
The assignment to the variable provides enough transparency that the static workspace mechanism is able to decide that the variable should exist.
However you should not count on this continuing to work exactly the same way: it is likely that at some point MATLAB will be changed so that only variables plainly assigned before the function call are considered to be known, or perhaps only variables plainly assigned to before the sub-function definition. Mathworks has been actively making the rules stricter recently.
4 个评论
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!