error Attempt to add (variable) to a static workspace, when it is not in workspace?
조회 수: 20 (최근 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!