Strange behavior of anonymous functions
조회 수: 1 (최근 30일)
이전 댓글 표시
Dear all,
I have two problems related to anonymous functions:
1-) I create an anonymous function taking several inputs inside a m-file function. Would like the anonymous function to take one input and use the other pre-created inputs from the workspace. for instance,
function f=myfunc(...)
a=rand(10,1); b=rand(10,1); c=rand(10,1); ss=rand(10,1);
f=@(x)a(6,:)*x^2+b(4,:)*x+c(3,:)-ss(5)
I get an error when calling the function I get an error saying that "ss" is undefined for inputs of type double and that I many need some toolbox that I do not have. But then I change the second line in the function to
f=@(x)a(6,:)*x^2+b(4,:)*x+c(3,:)-ss(5,:)
and everything works. Has anyone encountered such a problem? Is there any explanation for that behavior?
2-) After creating the anonymous function, I put it in a structure that I would like to carry around. The structure contains the anonymous function and various other elements. mystruct=struct(...,'anonym',myfunc(...)); I now would like to update the anonymous function inside the structure. In particular, I would like to change the order of input "x" before passing it to the anonymous function. I thought I could just create another anonymous function as follows neworder=10:-1:1; mystruct.anonym=@(x)mystruct.anonym(x(neworder));
This works without any problem. The issue is that when I now inspect the workspace of "mystruct.anonym" by issuing w=functions(mystruct.anonym), w.workspace, it contains an almost interminable loop of mystruct.anonym woven inside the sub-workspaces. This, most certainly, uses some memory. Is there any way to get rid of this behavior?
Thanks,
댓글 수: 3
Brendan Hamm
2015년 3월 13일
Also runs perfectly fine for me. I would check the original code and see if maybe you have a typo. Something like:
s = rand(10,1);
f=@(x)a(6,:)*x^2+b(4,:)*x+c(3,:)-ss(5)
답변 (1개)
per isakson
2015년 3월 13일
편집: per isakson
2015년 3월 13일
- If you have the Control or Signal Toolbox, ss as the name for variables used to cause trouble. See ss,Create state-space model, convert to state-space model. I once spent time to learn that:-(
- TMW is working on it. Not much we can do. Try to keep the workspace small when creating the anonymous function.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!