Writing functions f(x,y)
139 views (last 30 days)
Show older comments
How do I correctly write f(x,y)=4(x-1)^2+3(y-2)^2+2(x-2)^2(y-3)^2 in MatLab code for a fiminsearch? I have been trying for days and I still cant get it right. Please help!!!
0 Comments
Answers (4)
Stephen23
on 5 Sep 2023
Edited: Stephen23
on 5 Sep 2023
fh1 = @(x,y) 4*(x-1).^2 + 3*(y-2).^2 + 2*(x-2).^2.*(y-3).^2;
fh2 = @(v) fh1(v(1),v(2)); % function with one input
sol = fminsearch(fh2,[1,1])
val = fh2(sol)
An important part of any calculation is checking the result. Lets do that now:
fsurf(fh1)
hold on
plot3(sol(1),sol(2),val,'*r')
view(54,31)
Sam Chak
on 5 Sep 2023
Hi @Kaleina
For a static function, especially a function of two variables, this is how I systematically find the minimum point.
% STEP 1: Find the approximate location of the minimum point via contour plot
[X, Y] = meshgrid(-1:0.1:5); % adjust these until you see the basin
Z = staticfun(X, Y); % scroll to the bottom of the script
figure(1)
contour(X, Y, Z, 30), xline(1.5, '--'), yline(2.5, '--')
xlabel('x'), ylabel('y'), colorbar
% STEP 2: Find minimum of unconstrained function f(x, y)
funhd = @(v) staticfun(v(1), v(2)); % create a function handle to pass it to fminsearch
v0 = [1.5, 2.5]; % initial guess values based on the contour plot
solution = fminsearch(funhd, v0) % applying fminsearch
% STEP 3a: Plot the surface and the minimum point
figure(2)
surf(X, Y, Z), hold on
minValue = funhd(solution) % insert xsol & ysol into static funtion to find the min value
plot3(solution(1), solution(2), minValue, 'r.', 'MarkerSize', 25) % plot the red dot
% STEP 3b: rotate for better viewing
[az, el] = view;
az = az + 180;
view(az, el)
xlabel('x'), ylabel('y'), zlabel('f(x,y)')
% Part of STEP 1: to create a function for the surface f(x, y).
function fun = staticfun(x, y)
fun = 4*(x - 1).^2 + 3*(y - 2).^2 + 2*(x - 2).^2.*(y - 3).^2;
end
Alexander
on 6 Sep 2023
Edited: Alexander
on 6 Sep 2023
The solutions above are very good and should be used to avoid loops. But anyway I post my little script here, because I think it is good for the understanding how a multible dimension function is built up.
X = 0:0.1:4; % Taylor it to your needs (precision, boundary)
Y = X; % Y = -1:0.1:3;
for(ix = 1:length(X));
for(iy = 1:length(Y))
Z(ix,iy) = 4*(X(ix) - 1).^2 + 3*(Y(iy) - 2).^2 + 2*(X(ix) - 2).^2.*(Y(iy) - 3).^2;
end
end
figure(1); contour(X,Y,Z);xlabel('X');ylabel('Y');
figure(2); mesh(X,Y,Z);xlabel('X');ylabel('Y');ylabel('Z');
[C, ind] = min(Z); [zMin, xInd] = min(C);
[C, ind] = min(Z'); [zMin, yInd] = min(C);
fprintf('Minimum of Z: %3.4f at pos. [X,Y] = [%i, %i], value = [%3.4f, %3.4f]\n',zMin,xInd,yInd,X(xInd),Y(yInd))
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!