Error with using fminsearch

I want to convert a "function" with symbolic variables into an actual matlabfunction and search the minimum by using fminsearch. But I am getting an error saying that I havent got enough input arguments.
syms x y;
% Peaks Funktion
f = 3*(1-x)^2 * exp(-x^2-(y+1)^2)-10*(x/5-x^3-y^5)*exp(-x^2-y^2)-(exp(-(x+1)^2-y^2)/3);
f1 = matlabFunction(f);
gradient1 = gradient(f);
x0 = [4,3];
minimum = fminsearch(f1,x0);
I also tried
fminsearch(@(x,y) f1(x,y), x0);
but the error stays the same.
Does someone know what Im doing wrong?

Respuestas (1)

Star Strider
Star Strider el 21 de En. de 2024
Editada: Star Strider el 21 de En. de 2024
Yoiu need to add the 'Vars' argument to your matlabFunction call—
syms x y;
% Peaks Funktion
f = 3*(1-x)^2 * exp(-x^2-(y+1)^2)-10*(x/5-x^3-y^5)*exp(-x^2-y^2)-(exp(-(x+1)^2-y^2)/3);
% f1 = matlabFunction(f)
f1 = matlabFunction(f, 'Vars',{[x,y]}) % Creates Parameter Vector 'In1' Containing 'x' As 'In1(:,1)' And 'y' As 'In1(:,2)'
f1 = function_handle with value:
@(in1)exp(-(in1(:,1)+1.0).^2-in1(:,2).^2).*(-1.0./3.0)+exp(-(in1(:,2)+1.0).^2-in1(:,1).^2).*(in1(:,1)-1.0).^2.*3.0+exp(-in1(:,1).^2-in1(:,2).^2).*(in1(:,1).*-2.0+in1(:,1).^3.*1.0e+1+in1(:,2).^5.*1.0e+1)
gradient1 = gradient(f);
x0 = [4,3];
[minimum, fval] = fminsearch(f1,x0)
minimum = 1×2
27.1695 6.5127
fval = 0
Alternatively, you could create a separate funciton using the initial matlabFunction result as:
f1 = @(b) f(b(1),b(2));
however letting matlabFunction take care of those details is just easier.
EDIT — (21 Jan 2024 at 18:35)
Minor correction to add clarity. Code unchanged.
.

2 comentarios

Daniel
Daniel el 21 de En. de 2024
Thank you!
Star Strider
Star Strider el 21 de En. de 2024
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

Iniciar sesión para comentar.

Etiquetas

Preguntada:

el 21 de En. de 2024

Comentada:

el 21 de En. de 2024

Community Treasure Hunt

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

Start Hunting!

Translated by