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!