Why does the anonymous function not evaluate correctly

3 visualizaciones (últimos 30 días)
Hari
Hari el 29 de Jun. de 2014
Comentada: John D'Errico el 5 de Jul. de 2014
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

Respuesta aceptada

Star Strider
Star Strider el 29 de Jun. de 2014
Editada: Star Strider el 29 de Jun. de 2014
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 comentarios
Star Strider
Star Strider el 5 de Jul. de 2014
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 el 5 de Jul. de 2014
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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Symbolic Math Toolbox en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by