finding max and min of function graph

7 views (last 30 days)
Joseph
Joseph on 3 Apr 2014
Answered: Naga on 7 Apr 2025
Having trouble with last part of code: finding max and min. here is my code:
x = -10:1:10;
y = x;
[xGrid,yGrid] = meshgrid(x,y);
z = (1./((xGrid+3).^2 + (yGrid-1).^2 + 2)) + ((xGrid-yGrid) ./ ((xGrid-1) .^2 + (yGrid-2) .^2 + 4));
subplot(2,2,1)
surf(x,y,z)
title('Isometric View')
xlabel('X')
ylabel('Y')
zlabel('Z')
subplot(2,2,2)
surf(x,y,z)
az=0;
el=90;
view(az,el)
title('View Normal to X-Y Plane')
xlabel('X')
ylabel('Y')
zlabel('Z')
subplot(2,2,3)
surf(x,y,z)
view(0,0)
title('View Normal to X-Z Plane')
xlabel('X')
ylabel('Y')
zlabel('Z')
subplot(2,2,4)
surf(x,y,z)
az=90;
el=0;
view(az,el)
title('View Normal to Y-Z Plane')
xlabel('X')
ylabel('Y')
zlabel('Z')
NegFunction = @(x)(1./((x+3).^2 + (y-1).^2 + 2)) + ((x-y) ./ ((x-1) .^2 + (y-2) .^2 + 4));
[xyMaxVector,zMax] = fminsearch(NegFunction,[0,3]);
xMax = xyMaxVector(1);
yMax = xyMaxVector(2);
fprintf('The Max Value was: z(%6.3f,%6.3f) = %2.0f\n',xMax,yMax,-zMax)

Answers (1)

Naga
Naga on 7 Apr 2025
Hello Joseph,
It seems you're trying to find the maximum and minimum values of a function on a grid. While you've set up the plots and attempted to find the maximum using 'fminsearch' on the negative of the function, there are a couple of issues:
  1. The 'NegFunction' uses x and y, which are vectors, instead of defining a function that takes a single vector input [x, y]. This needs to be corrected.
  2. You only attempted to find the maximum using the negative of the function. You should also find the minimum directly using 'fminsearch'.
I made the suggested changes in the code below:
x = -10:1:10;
y = x;
[xGrid, yGrid] = meshgrid(x, y);
z = (1 ./ ((xGrid + 3).^2 + (yGrid - 1).^2 + 2)) + ((xGrid - yGrid) ./ ((xGrid - 1).^2 + (yGrid - 2).^2 + 4));
% Function for optimization
Function = @(v) -(1 ./ ((v(1) + 3).^2 + (v(2) - 1).^2 + 2)) - ((v(1) - v(2)) ./ ((v(1) - 1).^2 + (v(2) - 2).^2 + 4));
% Finding maximum
[xyMaxVector, negZMax] = fminsearch(Function, [0, 3]);
xMax = xyMaxVector(1);
yMax = xyMaxVector(2);
zMax = -negZMax; % Since we minimized the negative
% Finding minimum
FunctionMin = @(v) (1 ./ ((v(1) + 3).^2 + (v(2) - 1).^2 + 2)) + ((v(1) - v(2)) ./ ((v(1) - 1).^2 + (v(2) - 2).^2 + 4));
[xyMinVector, zMin] = fminsearch(FunctionMin, [0, 3]);
xMin = xyMinVector(1);
yMin = xyMinVector(2);
fprintf('The Max Value was: z(%6.3f,%6.3f) = %6.3f\n', xMax, yMax, zMax)
The Max Value was: z( 2.813, 0.026) = 0.276
fprintf('The Min Value was: z(%6.3f,%6.3f) = %6.3f\n', xMin, yMin, zMin)
The Min Value was: z( 0.137, 3.100) = -0.436

Categories

Find more on Functions 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!