error Attempt to add (variable) to a static workspace, when it is not in workspace?
16 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Steven Lord
2016-2-19
1 个评论
Stephen23
2018-6-29
编辑:Stephen23
2018-6-29
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!