simplegrid.m (705B)
1 % simplegrid.m 2 % 3 % Tests a simple grid search routine to be sure I know how it works. 4 % 5 % Consider minimizing the function f(x,y,z)=(x-1)^2+(y-2)^2+(z-3)^2. 6 7 x=(0:10)'; 8 y=(0:10)'; 9 z=(0:5)'; 10 11 Nx=length(x); 12 Ny=length(y); 13 Nz=length(z); 14 15 %uu=zeros(Nx,Ny,Nz); % contains the values of f(x,y,z); 16 17 % Use the ndgrid command instead of looping to create the values 18 [X Y Z]=ndgrid(x,y,z); 19 20 ff=(X-1).^2 + (Y-2).^2 + (Z-3).^2; 21 22 % So now we've got the function -- how do we find the index of its smallest 23 % element? 24 25 minval=min(min(min(ff))); % This is the minimum values 26 indx=find(ff==minval); % This is its index (1 to 27) 27 [a b c]=ind2sub([Nx Ny Nz],indx) % This converts index to subscripts 28 29 x(a) 30 y(b) 31 z(c)