Why does the anonymous function not evaluate correctly

3 次查看(过去 30 天)
I posted this in stack exchange comp science site 2 days back but couldn't get a response. Will restate with a simplified example and hope I get some directions.
Defining the following in a script (modifying matlab example for how x is inputted) and run it,
clc; clear;
anonrosen = @(x1,x2)(100*(x2 - x1^2)^2 + (1-x1)^2);
and then typing the following in command window,
anonrosen(-1,2)
yields,
ans =
104
But if I define the following in a script and run it,
clc; clear;syms x1 x2;
p = (100*(x2 - x1^2)^2 + (1-x1)^2);
anonrosen = @(x)p;
and then typing the following in command window,
anonrosen(-1,2)
yields,
ans =
(x1 - 1)^2 + 100*(- x1^2 + x2)^2
Why don't I get 104 as answer in 2nd approach?
The reason I want to make the 2nd approach work is the functional form "(100*(x2 - x1^2)^2 + (1-x1)^2)" in my application is being generated on the fly during application run depending on user inputs using symbolic toolbox so I cannot hard-code it the way it is done in matlab example code.
Thanks in advance Hari

采纳的回答

Star Strider
Star Strider 2014-6-29
编辑:Star Strider 2014-6-29
You have to define functions differently in the Symbolic Math Toolbox:
syms x1 x2
anonrosen = symfun(100*(x2 - x1^2)^2 + (1-x1)^2, [x1 x2])
anonrosen(-1,2)
produces:
anonrosen(x1, x2) =
(x1 - 1)^2 + 100*(- x1^2 + x2)^2
ans =
104
  11 个评论
Star Strider
Star Strider 2014-7-5
My pleasure!
I wanted to be sure I continued to monitor your question in the event we had not resolved it.
I’ll look for your next Question. Good call on creating it separately, since once an Answer is Accepted (THANKS!) it tends to not be followed-up.
John D'Errico
John D'Errico 2014-7-5
Don't close the question. Don't delete what you wrote. Don't do anything of the sort.
Leave the question there, for others to read and learn from it.
Then accept the answer if it solved your problem. Vote it up.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by