Created
November 10, 2015 22:27
-
-
Save normalhuman/e3bb689d6418df115c6c to your computer and use it in GitHub Desktop.
Simplified Nelder-Mead method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
f = @(x,y) 100*(x.^2-y).^2 + (x-1).^2; % Rosenbrock's function | |
x = -2:0.1:2; | |
y = -2:0.1:2; | |
[X,Y] = meshgrid(x,y); | |
contour (x,y, f(X,Y), 30); | |
hold on | |
T = [-2 -1; 2 0; -1 1]; | |
for i = 1:3 | |
z(i) = f(T(i,1),T(i,2)); | |
end | |
tol = 1e-6; | |
n = 0; | |
while (true) | |
h = fill(T(:,1),T(:,2),'k'); | |
set(h, 'FaceAlpha', 0); | |
[z,ix] = sort(z,'descend'); | |
T =T(ix,:); | |
if z(1)-z(3) < tol | |
disp(sprintf('Minimum found at (%.3f, %.3f) after %.d steps', T(3,1),T(3,2),n)); | |
break; | |
end | |
R = T(2,:)+T(3,:)-T(1,:); | |
fR = f(R(1),R(2)); | |
if fR < z(3) | |
E = 1.5*T(3,:)+1.5*T(2,:)-2*T(1,:); | |
fE = f(E(1),E(2)); | |
if fE < fR | |
T(1,:) = E; | |
z(1) = fE; | |
else | |
T(1,:) = R; | |
z(1) = fR; | |
end | |
else | |
for i=1:2 | |
T(i,:) = (T(i,:)+T(3,:))/2; | |
z(i) = f(T(i,1),T(i,2)); | |
end | |
end | |
n = n+1; | |
if n>= 200 | |
disp('Failed to converge'); break; | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment