Error with using fminsearch
Ältere Kommentare anzeigen
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?
Antworten (1)
Star Strider
am 21 Jan. 2024
Bearbeitet: Star Strider
am 21 Jan. 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)'
gradient1 = gradient(f);
x0 = [4,3];
[minimum, fval] = fminsearch(f1,x0)
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 Kommentare
Daniel
am 21 Jan. 2024
Star Strider
am 21 Jan. 2024
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.
Kategorien
Mehr zu Code Performance finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!