## Example of bad optimization with fminsearch (Nelder & Mead Simplex algorithm)
clear all
XXX = [1,4,9];      % set simple 3D grid
[X1,X2,X3]=ndgrid(XXX);
nt = length(X1(:))  % total number of points in grid
for i=1:nt %sweep through points in grid
  Ft(:,i) = [X1(i)^2+X2(i)^2+X3(i)^2; 1+X1(i)^2+X2(i)^2+X3(i)^2];
  %each point in grid has two outcomes to replicate my problem
end
Ft = reshape(Ft, size(Ft,1), 3,3,3);  %reshape grid to 2x3x3x3
maxFt = max(Ft(:))  %output maximum value to doublecheck 
%it's 244 at grid point (2,3,3,3) as 2nd value at coordinates 9,9,9 
fun = @(r) -interp3 (XXX,XXX,XXX,squeeze(Ft(2,:,:,:)),r(2),r(1),r(3),'linear',0)
%maximize values of 2nd layer as in my problem
%swap 2nd input with first input because interp3 follows meshgrid arrangement
%but ndgrid follows vectorial arrangement as in my problem
%- sign because I want to maximize, and set it to 0 outside boundaries
options = optimset ('Display', 'iter');
[p, objf, cvg, outp] = fminsearch ( fun, [1,1,1], options)
%fminsearch should converge to minimum -244 at 2nd layer point 9,9,9
%instead it stops at 9,9,8.7 why?
