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?
답변 (1개)
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
Daniel
2024년 1월 21일
Star Strider
2024년 1월 21일
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.
카테고리
도움말 센터 및 File Exchange에서 Code Performance에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!