close all
clear
clc
x1_bounds = [0 5];
x2_bounds = [0 5];
SearchMode = 1;
SearchPoints = 5;
StepSize = 1;
BestGuess = [2.5, 2.5];
if SearchMode == 1
x0(1,:) = (x1_bounds(1,2)-x1_bounds(1,1)).*rand(1,SearchPoints) + x1_bounds(1,1);
x0(2,:) = (x2_bounds(1,2)-x2_bounds(1,1)).*rand(1,SearchPoints) + x2_bounds(1,1);
end
clear SearchPoints
if SearchMode == 2
ndg = x1_bounds(1):StepSize:x1_bounds(2);
[X,Y] = ndgrid(ndg,ndg);
sizeX = size(X);
sizeY = size(Y);
x0(1,:) = reshape(X,[1,sizeX(1)*sizeX(2)]);
x0(2,:) = reshape(Y,[1,sizeY(1)*sizeY(2)]);
end
clear sizeX sizeY X Y ndg StepSize
if SearchMode == 3
x0 = BestGuess;
end
solutionSet = ones(2,length(x0))*999999999;
fvalSet = ones(1,length(x0))*999999999;
iter_Total = 0;
feval_Total = 0;
options2 = optimoptions('fmincon','MaxFunctionEvaluations',3500,'PlotFcn',...
{'optimplotx','optimplotfunccount','optimplotfvalconstr','optimplotfval',...
'optimplotconstrviolation','optimplotstepsize','optimplotfirstorderopt'},'Algorithm','sqp');
for i=1:1:length(x0)
[solution,objectiveValue,exitflag,output] = fmincon(@objectiveFcn,x0(:,i),[],[],[],[],...
zeros(size(x0)),repmat(5,size(x0)),[],options2);
solutionSet(:,i) = solution;
fvalSet(1,i) = objectiveValue;
iter_Total = iter_Total + output.iterations;
feval_Total = feval_Total + output.funcCount;
end
clear solution i objectiveValue output exitfflag
clearvars options2
[Minimum_F, index] = min(fvalSet);
X_star = [solutionSet(1,index) solutionSet(2,index)];
if SearchMode == 1 || SearchMode == 2
subplot(3,3,9)
scatter(x0(1,:),x0(2,:),'o','b')
hold on
scatter(X_star(1),X_star(2),'*','r')
hold off
hold on
scatter(x0(1,index),x0(2,index),'x','g')
hold off
xlabel('x1')
ylabel('x2')
title('Search Points')
axis(horzcat(x1_bounds,x2_bounds))
end
subplot (3,3,8)
meshDensity = 20;
[X,Y] = ndgrid(linspace(x1_bounds(1),x1_bounds(2),meshDensity),...
linspace(x2_bounds(1),x2_bounds(2),meshDensity));
myFun = @(x,y) 2+0.01.*(y-x.^2).^2 + (1-x).^2 + 2.*(2-y).^2 + 7.*sin(0.5.*x).*sin(0.7.*x.*y);
s = meshc(X,Y,myFun(X,Y),'FaceAlpha','0.5');
s(1).FaceColor = 'flat';
s(2).FaceColor = 'flat';
s(2).Fill = 'on';
colorbar
xlabel('x1')
ylabel('x2')
zlabel('f(X'')')
title('Function Plot')
axis tight
camzoom(1)
clear meshDensity s x_int y_int X Y myFun
hold on
scatter3(X_star(1),X_star(2),Minimum_F,'*','r')
hold on
f = objectiveFcn([x0(1,index);x0(2,index)]);
scatter3(x0(1,index),x0(2,index),f,'o','g')
hold off
clear f
iter_Total
feval_Total
function f = objectiveFcn(optimInput)
x = optimInput(1);
y = optimInput(2);
f = 2+0.01*(y-x^2)^2 + (1-x)^2 + 2*(2-y)^2 + 7*sin(0.5*x)*sin(0.7*x*y);
end
0 Comments
Sign in to comment.