error Attempt to add (variable) to a static workspace, when it is not in workspace?
25 views (last 30 days)
Show older comments
Why does this function generate
function bug
clear all;
syms y(idx)
foo()
function r = foo()
r=y(1);
end
end
error is
Error using assignin
Attempt to add "y" to a static workspace.
See Variables in Nested and Anonymous Functions.
Error in syms (line 106)
assignin('caller', name, symfun(xsym, [vars{:}]));
Error in bug (line 3)
syms y(idx)
I do not have `y` in workspace. It is defined inside function, and I want to access it from inside an inner function. So why is Matlab saying the above? If I make the inner function another separate, but inside the same m file. It works.
function bug
clear all;
syms y(idx)
foo(y)
end
function r = foo(y)
r=y(1);
end
I am using Matlab 2015a, windows 7.
0 Comments
Answers (1)
Steven Lord
on 19 Feb 2016
1 Comment
Stephen23
on 29 Jun 2018
Edited: Stephen23
on 29 Jun 2018
It's the way you're adding y to the workspace that's the problem. A simpler reproduction step for this behavior:
function NOTbug
eval('y = 42;')
foo()
function r = foo()
r = y(1);
end
end
This is everyone's favorite "poofing" problem combined with the restrictions on what you're allowed to do in the workspace of a nested function.
> It is defined inside function, and I want to access it from inside an
> inner function. So why
> is Matlab saying the above? If I make the inner function
> another separate, but inside the same m file. It works.
Yes, because the rules are different for subfunctions than they are for nested functions. The documentation page to which the error message linked is:
Why is this relevant, you ask, since you're not using LOAD, EVAL, EVALIN, ASSIGNIN, calling a script, or defining variables in the debugger? YOU aren't doing any of those things ... but SYMS is. Specifically, SYMS uses ASSIGNIN to create the symbolic variable in its caller's workspace. [That's the reason one of the tips on its documentation page says not to use it to create variables with the same name as a MATLAB function. That would be "poofing", just like if you used EVAL to create a variable with that name or LOADed such a variable from a MAT-file.] Normally this use of ASSIGNIN isn't a problem, but in a nested function it is.
The solution is to define the variables in your symbolic expression explicitly in the code. Changing the variables isn't a problem; "poofing" them into the workspace is.
function NOTbug
y = [];
idx = [];
syms y(idx)
foo()
function r = foo()
r = y(1);
end
end
--
Steve Lord
To contact Technical Support use the Contact Us link on
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!