What is the cause of this weird phenomenon with symbolic variables and nested function?

15 views (last 30 days)
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?

Accepted Answer

Walter Roberson
Walter Roberson on 29 Jan 2020
Edited: Walter Roberson on 8 Feb 2023
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 Comments

Sign in to comment.

More Answers (0)

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!