Finding x and y values of minimum z in 2-variable function.
Show older comments
I'm using for loops to find a minimum of z(x,y) as well as the x and y of that value.
With a step size of 1 it finds the right values, but with a step size of 0.1 the y value is 10 when it should be around 2.
Any help would be appreciated.
[x,y] = meshgrid(0:0.1:10, 0:0.1:10);
z = (x.^2).*(y.^3)-1.4*(x.^2).*(y.^2)-3.91*(x.^2).*y+5.78*(x.^2)-...
11*x.*(y.^3)+15.4*x.*(y.^2)+43.01*x.*y-63.58*x+30.25*(y.^3)-...
42.35*(y.^2)-118.278*y+174.845;
min = 100;
for i=1:101
for j=1:101
if z(i,j)<min
min = z(i,j);
xmin = x(i,j);
ymin = y(i,j);
end
end
end
1 Comment
John D'Errico
on 27 Feb 2025
Note that it is a really bad idea to use a variable neamed min, as then later on when you need to use the function min, MATLAB will not know how to distinguish between the function and variable.
Answers (3)
The continuous minimum can't be at (5,2) as you claim. Direct evaluation shows that the value of z at (5.5,10) is lower.
loopingMin(1)
loopingMin(0.1)
function loopingMin(stepsize)
[x,y] = meshgrid(0:stepsize:10, 0:stepsize:10);
z = (x.^2).*(y.^3)-1.4*(x.^2).*(y.^2)-3.91*(x.^2).*y+5.78*(x.^2)-...
11*x.*(y.^3)+15.4*x.*(y.^2)+43.01*x.*y-63.58*x+30.25*(y.^3)-...
42.35*(y.^2)-118.278*y+174.845;
minval = inf;
for i=1:height(x)
for j=1:width(y)
if z(i,j)<minval
minval = z(i,j);
xmin = x(i,j);
ymin = y(i,j);
end
end
end
xmin,ymin,minval
end
Is there a particular reason to use that sort of iteration? MATLAB has a number of optimization funcitons you can use, with fminsearch being a part of core MATLAB (no Toolboxes required) or one of the Optimization Toolbox functions, such as fsolve
That aside, I keep getting different results betweeen runs and between functions —
z = @(x,y) (x.^2).*(y.^3)-1.4*(x.^2).*(y.^2)-3.91*(x.^2).*y+5.78*(x.^2)-...
11*x.*(y.^3)+15.4*x.*(y.^2)+43.01*x.*y-63.58*x+30.25*(y.^3)-...
42.35*(y.^2)-118.278*y+174.845;
B0 = randn(2,1)
[B,fv] = fminsearch(@(b) norm(z(b(1),b(2))), B0)
zval = z(B(1),B(2))
[B,fv] = fsolve(@(b) norm(z(b(1),b(2))), B0)
zval = z(B(1),B(2))
[B,fv] = fminunc(@(b) norm(z(b(1),b(2))), B0)
[X,Y] = ndgrid(linspace(min(B)-0.1*abs(min(B)), max(B)+0.1*abs(max(B)), 250));
figure
surfc(X, Y, z(X,Y), EdgeColor='interp', FaceAlpha=0.1)
hold on
stem3(B(1), B(2), z(B(1),B(2))+5, 'vr', MarkerFaceColor='r')
hold off
grid
zlim([min([zval zlim]) max(zlim)])
xlabel('X')
ylabel('Y')
zlabel('Z')
colormap(turbo)
view(60,30)
grid on
.
z = @(x,y)(x.^2).*(y.^3)-1.4*(x.^2).*(y.^2)-3.91*(x.^2).*y+5.78*(x.^2)-...
11*x.*(y.^3)+15.4*x.*(y.^2)+43.01*x.*y-63.58*x+30.25*(y.^3)-...
42.35*(y.^2)-118.278*y+174.845;
sol = fmincon(@(u)z(u(1),u(2)),[1 1],[],[],[],[],[0 0],[10 10])
z(sol(1),sol(2))
Categories
Find more on Mathematics 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!